4
As many know (I believe) a multidimensional matrix is stored in memory in a linear way, that is, each line of the matrix goes in memory one after the other. To illustrate I elaborated the following image:
Thus, it is possible to manipulate a multidimensional matrix as if it were a vector using a pointer:
#include <stdio.h>
#define ROWS 4
#define COLUMNS 4
int main(void){
int matrix[ROWS][COLUMNS]={{17, 10, 14, 78},
{4, 14, 15, 10},
{14, 45, 56, 70},
{47, 15, 49, 10}};
int *ptr=matrix[0];
for(unsigned int i=0; i<(ROWS*COLUMNS); i++){
printf("[%d] ", ptr[i]);
}
printf("\n\n\n");
ptr=NULL;
return 0;
}
Knowing this, I tried to apply this same concept to a two-dimensional matrix that was dynamically allocated, but when accessing the elements via command for
(as in the example above) I ended up getting garbage on the output, ie values that were not in the matrix. Follows the code of "program":
#include <stdio.h>
#include <stdlib.h>
#define ROWS 4
#define COLUMNS 4
int main(void){
int **matrix=(int**)malloc(ROWS*sizeof(int*)); //Alocando as linhas da matriz
for(unsigned int i=0; i<ROWS; i++){
matrix[i]=(int*)malloc(COLUMNS*sizeof(int)); //Alocando as colunas
}
//Preenchendo a matriz
for(unsigned int row=0; row<ROWS; row++){
for(unsigned int column=0; column<COLUMNS; column++){
matrix[row][column]=42; //42? Seria isso a resposta para "tudo"?
}
}
int *ptr=matrix[0];
//Exibindo valores
for(unsigned int i=0; i<(ROWS*COLUMNS); i++){
printf("[%d] ", ptr[i]);
}
printf("\n\n\n");
for(unsigned int column=0; column<COLUMNS; column++){
free(matrix[column]); //Desalocando as colunas da matriz
}
free(matrix); //Desalocando as linhas da matriz
ptr=NULL;
return 0;
}
When I execute the code:
[42] [42] [42] [42] [-2074264339] [134268537] [42] [42] [42] [42] [-2074264339] [134268537] [42] [42] [42] [42]
Why is the displayed result not similar to the first code? What’s wrong?
Whose exactly are these printed addresses?
– user105951
These are the addresses of the next vector, according to the above drawing. But, as I said in the reply, there is no guarantee that the printed values will always be those. The
malloc
can allocate blocks in different locations– Gomiero