Why does the following code output 4?
char** pointer = new char*[1];
std::cout << sizeof(pointer) << "\n";
I have an array of pointers, but it should have length 1, shouldn't it?
If you are on a 64 bit computer, the memory addresses are 64 bit, therefore a 64 bit (8 bytes x 8 bits per byte) numeric value must be used to represent the numeric pointer variable (char*). In other words, sizeof() works the same way for pointers as for standard variables.
Size of a pointer is fixed for a compiler. All pointer types take same number of bytes for a compiler. That is why we get 4 for both ptri and ptrc.
An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
Your machine seems to have 64 bit addresses, and thus, each address (and hence, each pointer) is 64 bits (8 bytes) long. a[0] , on the other hand, is of the type that an element of that array has (an int ), and that type has 32 bits (4 bytes) on your machine.
pointer
is a pointer. It is the size of a pointer, which is 4 bytes on your system.
*pointer
is also a pointer. sizeof(*pointer)
will also be 4.
**pointer
is a char. sizeof(**pointer)
will be 1. Note that **pointer is a char because it is defined as char**
. The size of the array new`ed nevers enters into this.
Note that sizeof
is a compiler operator. It is rendered to a constant at compile time. Anything that could be changed at runtime (like the size of a new'ed array) cannnot be determined using sizeof
.
Note 2: If you had defined that as:
char* array[1];
char** pointer = array;
Now pointer
has essencially the same value as before, but now you can say:
int arraySize = sizeof(array); // size of total space of array
int arrayLen = sizeof(array)/sizeof(array[0]); // number of element == 1 here.
sizeof
always returns a number of bytes.
Here, pointer
is an ... err ... pointer and is 32 bits on 32 bits architectures, i.e. 4 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With