How to create a matrix with dynamic allocation and structs

Asked

Viewed 94 times

1

I know how to create a matrix using dynamic allocation only. However, I’m not able to create using structures.

I have the following struct:

struct matriz{
    int** elemento;
    int nlinhas;
    int ncolunas;
};

and I used typedef to make it easier:

typedef struct matriz Matriz;

So I tried to implement the following function:

Matriz* inicializaMatriz(int nlinhas, int ncolunas){
    Matriz* mat;

    mat = (Matriz*)malloc(sizeof(int));
    mat->nlinhas = (int*)malloc(sizeof(int) * nlinhas);
    mat->ncolunas = (int*)malloc(sizeof(int) * ncolunas);

    return mat;
}

However, when I try to implement this other function that will assign values to each element of the matrix:

void modificaElemento(Matriz* mat, int linha, int coluna, int elem){
    mat[linha][coluna]->elemento = elem;
}

I get the message that it is not possible(subscrited value is neither array nor Pointer nor vector)

With this, I would like help to create a matrix using the structure already mentioned.

  • If in your Matrix struct nlinhas and ncolunas are int fields so the assignments: mat->nlinhas = (int*)malloc(sizeof(int) * nlinhas); and mat->ncolunas = (int*)malloc(sizeof(int) * ncolunas); make no sense.

  • but I don’t have to allocate memory for rows and columns?

1 answer

2


Its allocation is not correct in several parts, and this refers specifically to the function inicializaMatriz. This one should look like this:

Matriz* inicializaMatriz(int nlinhas, int ncolunas){
    Matriz* mat = malloc(sizeof(Matriz)); //criar primeiro o elemento da estrutura
    mat->elemento = malloc(sizeof(int*) * nlinhas); //aloca a matriz dentro da estrutura
    mat->nlinhas = nlinhas; //coloca o numero de linhas dentro da estrutura
    mat->ncolunas = ncolunas; //coloca o numero de colunas dentro da estrutura

    //percorre cada linha com um for para criar as colunas
    int i;
    for (i = 0; i < nlinhas; ++i){
        mat->elemento[i] = malloc(sizeof(int) * ncolunas);
    }

    return mat;
}

I noted all the differences with comments. Watch how the creation of the mat->elemento is with the sizeof(int*) and the columns are with sizeof(int), that was one of the problems I had previously.

The modification part is also not correct, because the elemento is that it is the matrix and not the mat. Change to:

void modificaElemento(Matriz* mat, int linha, int coluna, int elem){
    mat->elemento[linha][coluna] = elem;
}

With these changes already works, as you can see in Ideone.

Browser other questions tagged

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