I can create a two dimensional array in c++ in the following way. But I'm having trouble understanding the memory addressing.
(Please note the last line of my code where I try to print the decimal values of the memory locations.)
#include <cstdio>
#include <iostream>
using namespace std;
#define rowSize 3
#define colSize 4
int main(){
int ** p;
p = new int*[rowSize];
for(int i = 0; i < rowSize; i++){
p[i]= new int[colSize];
}
printf("the size of int**: %d\n", sizeof(int**));
printf("the size of int*: %d\n", sizeof(int*));
printf("the size of int: %d\n\n", sizeof(int));
printf("%d %d", p[0], p[1]);
return 0;
}
I used gcc version 4.7.1 (tdm-1) compiler and ran my program on my windows 10- 64 bit machine.
Here is a sample output:
the size of int**: 4
the size of int*: 4
the size of int: 4
8135000 8135024
So, here are my two questions:
Why do the addresses differ by 24 instead of 16 (= 4*4) ? The size of int is 4 and there are 4 columns in a row. So shouldn't they differ by 16? I know about byte padding in structure in c++. Is something like this the reason behind it?
I tried changing the colSize to 5:
#define colSize 5
and recompiled and ran the program again.A sample output:
the size of int**: 4 the size of int*: 4 the size of int: 4 7151960 7151992
This time the addresses differ by 32. If byte padding was the reason, the 5 columns would require 5*4 = 20 bytes. A padding of 4 bytes would be sufficient in this case, and the addresses should differ by 24 in this case too.
So why are they differing by 32 in this case?