As many know (I believe) a multidimensional array is stored in memory in a linear fashion, ie each row of the array goes into memory one after the other. For example, I created the following image:
Soyoucanmanipulateamultidimensionalarrayasifitwereavectorusingapointer:
#include<stdio.h>#defineROWS4#defineCOLUMNS4intmain(void){intmatrix[ROWS][COLUMNS]={{17,10,14,78},{4,14,15,10},{14,45,56,70},{47,15,49,10}};int*ptr=matrix[0];for(unsignedinti=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 array that was dynamically allocated, but at the time of accessing the elements via the for
command (as in the example above) I ended up receiving garbage on output, which were not in the womb. Here is the code for the "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 run the code:
[42] [42] [42] [42] [-2074264339] [134268537] [42] [42] [42] [42] [-2074264339] [134268537] [42] [42] [42] [42]
Why does not the result displayed look like the first code? What's wrong?