I want to declare a 2d array using malloc. On looking up on the internet, all websites tell to declare a int ** pointer and then use malloc for first allocating the individual pointers to the 1d arrays and then use malloc again to allocate space for the individual ints. My doubt is that the array declared this way does not hold its elements in contiguous memory addresses. While the following way using only one malloc statement and dynamically allocates a 2d array and all the addresses are contiguous as required. So shouldn't the following be the correct way to dynamically allocate a 2d array?
#include <stdio.h>
int main(){
int (*p)[2] = malloc(3 * sizeof *p);
int i;
int j;
//All addresses printed here are contiguous
for(i=0; i<3; i++){
for(j=0; j<2; j++){
printf("%d\t", &p[i][j]);
}
printf("\n");
}
}