I have read in several places that allocating multidimensional arrays as such is inefficient and should be avoided.
int main(){
int** arr2d = malloc(3*sizeof(int*));
for(int m = 0; m < 3 ; ++m){
arr2d[m] = malloc(sizeof(int)*3);
}
for(int m = 0 ; m < 3 ; ++m){
for(int n = 0; n < 3; ++n){
arr2d[m][n] = m+n;
}
}
for(int m = 0 ; m < 3 ; ++m){
for(int n = 0; n < 3; ++n){
printf("%d,",arr2d[m][n]);
}
printf("\n");
}
for(int m = 0; m < 3 ; ++m){
free(arr2d[m]);
}
free(arr2d);
return 0;
}
The alternative would be to allocate an array enough for m*n and index it accordingly giving the idea of 2D
int main(){
int* arr = malloc(9*sizeof(int));
for(int m = 0; m < 3; ++m){
for(int n = 0; n < 3; ++n){
int index = m*3+n;
arr[index] = m+n;
}
}
for(int m = 0; m < 3; ++m){
for(int n = 0; n < 3; ++n){
int index = m*3+n;
printf("%d,",arr[index]);
}
printf("\n");
}
free(arr);
return 0;
}
What I'm wondering is how much of a difference in terms of resource usage and timing does that really make? I know in the first example a total of 32 bytes are allocated and in the second example 27 bytes are allocated. When dealing with much larger matrices I can see that making a difference but does time complexity change or does it not matter since you're looping m*n number of times regardless? Should I always follow the second example as basically standard?