Pointer array and sizeof confusion
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?
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.
When you call sizeof you're asking for how large it is in terms of bytes. A pointer is actually an integer that represents an address where the data you're pointing to is, and assuming that you're using a x32 operating system the size of an int is 4 bytes.
pointer
is of type char**
, whic has size of 4
what you might want is char * pointer [1]
but to have the length of such array you need the following code
int len = sizeof(pointer)/sizeof(char*)
check this out:
int * pArr = new int[5];
int Arr[5];
sizeof(pArr); //==4 for 32 bit arch
sizeof(Arr); //==20 for 32 bit arch
sizeof(Arr)/sizeof(int); //==5 for any arch
sizeof
does not give you the size of dynamic arrays (whose size is only determined at run-time, and could be of different size during different executions).
sizeof
is always evaluated at compile-time and it gives you the size of the type in question, in this case the type is char**
- a pointer (to pointer).
It is your task to keep track of the size of dynamically allocated arrays (you know how much you requested in the first place). Since it is a burden, all the more reason to use containers and the string class, which keep track of the allocation size themselves.
精彩评论