How to reference mat[x][y] in pointer notation

Asked

Viewed 211 times

1

I’m working with programming in c, with pointers and dynamic allocation, need to respond to an exercise that asks for the following:

How to reference mat[x][y] in pointer notation.

  • How you allocated the matrix?

  • I never worked well with matrix, but usually with vectors I do the following: vector = (int *)malloc(10 * sizeof(int)); if (vector == NULL) { printf("I could not ALLOCATE MEMORY. n"); Return -1; }

  • So you allocate it linearly as a vector?

  • This, I believe that the exercise is asking me to do the same, but now with a vector vector, what I did not understand exactly.

1 answer

4


Vector vectors with dynamic allocation are basically Jagged arrays.

The initial vector will become a pointer vector, pointing each of its boxes to another vector. The following figure illustrates this concept well:

inserir a descrição da imagem aqui

This causes the matrix to have to be defined as a pointer to pointer:

int **matriz = malloc(sizeof(int) * 10); //10 linhas

For each of the lines defined it is necessary to create the respective vector with the number of columns through a loop/cycle:

int i;
for (i = 0; i <10; ++i){
    matriz[i] = malloc(sizeof(int)*10); //cada linha tem 10 colunas
}

After this we have a 10 by 10 matrix that was dynamically allocated. This can now be used normally as one that has been statically allocated.

Memory release

Also remember that once it’s been dynamically allocated, you’re responsible for dislocating it when you don’t need it by invoking the free. This will be perhaps more elaborate than you think once you have to first dislocate the sub-vectors and then the main matrix:

for (i = 0; i < 10; ++i){
    free(matriz[i]);
}

free(matriz);

Browser other questions tagged

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