Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizeof Pointer to Array

Tags:

c++

pointers

If I have an array declared like this:

int a[3][2];

then why is:

sizeof(a+0) == 8

whereas:

sizeof(a)   == 24

I don't understand how adding 0 to the pointer changes the sizeof output. Is there maybe some implicit type cast?

like image 610
user695652 Avatar asked Oct 13 '11 19:10

user695652


People also ask

What is the size of a pointer to an array?

The pointer ptr, and all pointers, are 8 bytes, because they hold addresses, which are 8 bytes, or 64 bits. Assigning any address to an array variable is not allowed.

Can you use sizeof on a pointer?

The sizeof( ) operator is used to find the memory occupied by a data type, an expression, or a pointer.

Can you use sizeof on an array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


1 Answers

If you add 0 to a, then a is first converted to a pointer value of type int(*)[2] (pointing to the first element of an array of type int[3][2]). Then 0 is added to that, which adds 0 * sizeof(int[2]) bytes to the address represented by that pointer value. Since that multiplication yields 0, it will yield the same pointer value. Since it is a pointer, sizeof(a+0) yields the size of a pointer, which is 8 bytes on your box.

If you do sizeof(a), there is no reason for the compiler to convert a to a pointer value (that makes only sense if you want to index elements or to do pointer arithmetic involving the address of the elements). So expression a stays being of an array type, and you get the size of int[3][2] instead the size of int(*)[2]. So, 3 * 2 * sizeof(int) which on your box is 24 bytes.

Hope this clarifies things.

like image 122
Johannes Schaub - litb Avatar answered Sep 22 '22 00:09

Johannes Schaub - litb