I wanted achieve 2D array with double pointer and I expected each array to be contiguous in memory space. So there should be 20-bytes between each array. But following code giving different result which I supposed. Can anyone explain why each array not be contiguous?
#define ROW 5
#define COL 5
int main() {
int **ptr = (int **)malloc(sizeof(int *)*ROW);
for(int i=0; i<ROW; i++) {
*(ptr+i) = (int *)malloc(sizeof(int)*COL);
}
printf("%p\n", *(ptr+0));
printf("%p\n", *(ptr+1));
printf("%p\n", *(ptr+2));
printf("%p\n", *(ptr+3));
return 0;
}
Output :
0000 0df3 4325 1450
0000 0df3 4325 1470
0000 0df3 4325 1490
0000 0df3 4325 14b0
Expected :
0000 0df3 4325 1450
0000 0df3 4325 1464
0000 0df3 4325 1478
0000 0df3 4325 148c
malloc()allocates each array at an aligned address so it can be used for any datatype. There also may be some overhead bytes. So you shouldn't expect each array to be right next to the previous one.ptr[i]instead of*(ptr+i).%pprintf specifier requires an argument of typevoid *. By passing an argument ofint *instead without a cast tovoid *, according to the C standard, you are invoking undefined behavior. Nevertheless, on most modern platforms, the cast tovoid *is unnecessary.