2

I'm currently taking a C++ course and we are learning about pointers. The following is an example my professor gave us.

int b[3][3];  //Assume integers and memory addresses are 4 bytes
cout << sizeof(b) << endl;  // 36 bytes
cout << sizeof(b+0) << endl;  // 4 bytes
cout << sizeof(*(b+0)) << endl;  //12 bytes

I have 2 questions:

  1. I tried the second one (sizeof(b+0)) and it gives me 8 instead? How come that is the case?

  2. Also I want to understand the logic behind the third one (sizeof(*(b+0)); is it 12 because it is the total of the first row? Since there are 3 ints and each int is 4 bytes thus it returns 12 bytes in total?

Any help is much appreciated!

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
xfreak
  • 41
  • 3

2 Answers2

1

Sizeof function to ..

sizeof is an operator, not a function. Read more in Why is sizeof considered as an operator?

it gives me 8 instead?

It decays to a pointer.

is it 12 because it is the total of the first row?

Yes. It's like having a 1D array of 3 integers.


You might want to check these too:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp 
main.cpp:8:21: warning: sizeof on pointer operation will return size of
      'int (*)[3]' instead of 'int [3][3]' [-Wsizeof-array-decay]
    cout << sizeof(b+0) << endl; // 4 bytes
                   ~^
1 warning generated.
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
36
8
12
4 // sizeof(int)
8 // sizeof(int*)

About the warning:

"This warning is telling you that if you call sizeof(int[]) you won't get the size of the array but the size of an int* pointer."

taken from this answer.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

1) In systems with 64bits addresses, the pointer have 8 bytes, 64/8.

2) The 2D array is stored as an array of pointers to arrays. So when you do the *(b+0), it is giving to you the contents of the first position of the array b, which is an array of 3 ints. *(b+0) is equivalent to b[0].