How to store arrays in vectors in C?

Asked

Viewed 99 times

-1

I need to create a vector that stores matrices and print these matrices. What would be the correct way to do the assignment and print the matrices through the vet?

int main()
{
    int *vet;
    int **mat;
    int i, j;

    vet = (int*)malloc(2*sizeof(int));

    mat = (int **) malloc (2 * sizeof (int*)); 
    for( i=0; i<2 ; i++) {
        mat[i] = (int*) malloc (3 * sizeof(int));
    }
    
    //Atribuir matriz ao vetor
    

    //Preencher matrizes
    for( i=0; i<2 ; i++) {
        for( j=0; j<3 ; j++) {
            mat[i][j] = 1;
        }
    }

    //Imprimir matrizes
    for(i = 0; i < 2; i++) {
        //printf(" %d \n", vet[i]);
    }

}

1 answer

0


A matrix vector can also be seen as a three-dimensional matrix, we can represent this type of data using a variable that stores addresses for address lists. As follows.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int ***vet;
    int item;
    int *linha;
    int **mat;
    vet = malloc(2 * sizeof(int **));
    //Preencher as matrizes
    for (int i = 0; i < 2; i++) {//percorre cada matriz 
        mat = malloc(3 * sizeof(int *));
        for (int j = 0; j < 3; j++) {//percorre cada linha de uma matriz
            linha = malloc(3 * sizeof(int));
            for (int k = 0; k < 3; k++) {//percorre cada elemento de uma linha
                item = i * j;  //regra qualquer de preenchimento
                linha[k] = item;
            }
            mat[j] = linha;
        }
        vet[i] = mat;
    }
    //matriz preenchida
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("|");
            for (int k = 0; k < 3; k++) {
                printf("%d", vet[i][j][k]);
                printf("|");
            }
            printf("\n");
        }
        printf("\n");
    }
}

In this example I made two matrices 3*3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.