Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does the following code output 4?

char** pointer = new char*[1];
std::cout << sizeof(pointer) << "
";

I have an array of pointers, but it should have length 1, shouldn't it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
584 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...