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

1

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

  

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

    
asked by anonymous 16.10.2017 / 02:43

1 answer

4

Vector vectors with dynamic allocation are basically jagged arrays .

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

This causes the array to be defined as a pointer to pointer:

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

For each of the defined rows it is necessary to create its vector with the number of columns through a loop / loop:

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 normally be used as one that has been statically allocated.

Memory release

Also remember that once it has been allocated dynamically you are responsible for the deallocation when you do not need it by invoking free . This will perhaps be more elaborate than you think since you have to deallocate the sub-vectors first and then the main matrix:

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

free(matriz);
    
16.10.2017 / 03:41