About multi level pointer
Sep 29, 2022 at 7:23am UTC
Here is a code about multi level pointer:
1 2 3 4 5 6
double * (*a)[3][6];
cout << sizeof (a) << endl; // 4
cout << sizeof (*a) << endl; // 72
cout << sizeof (**a) << endl; // 24
cout << sizeof (***a) << endl; // 4
cout << sizeof (****a) << endl; // 8
I am confused about the output of the code. Can someone help me analyse the meaning of every expression in sizeof and how can I analyse it?
Thanks for your help.
Sep 29, 2022 at 7:45am UTC
Think about what type each expression is.
cout << sizeof (a) << endl; // 4
a is a
pointer to an array of 3 arrays of 6 pointers to double. On your system/with your compiler a pointer seems to be
4 bytes .
cout << sizeof (*a) << endl; // 72
*a is an
array of 3 arrays of 6 pointers to double. Since the size of a pointer is 4 bytes and you have 3×6 pointers the total size is 3×6×4=
72 bytes .
cout << sizeof (**a) << endl; // 24
**a is an
array of 6 pointers to double. 6×4=
24 bytes .
cout << sizeof (***a) << endl; // 4
***a is a
pointer to double. As we have said before, the size of a pointer for you is
4 bytes .
cout << sizeof (****a) << endl; // 8
****a is a
double which is
8 bytes .
If we replace the expressions with types instead your code will look like this:
1 2 3 4 5
cout << sizeof (double *(*)[3][6]) << endl; // 4
cout << sizeof (double *[3][6]) << endl; // 72
cout << sizeof (double *[6]) << endl; // 24
cout << sizeof (double *) << endl; // 4
cout << sizeof (double ) << endl; // 8
This code is equivalent to what you had and will give the same outputs.
Last edited on Sep 29, 2022 at 7:58am UTC
Sep 29, 2022 at 8:02am UTC
Thanks a lot for your detailed reply. I got it.
Topic archived. No new replies allowed.