Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer array and sizeof confusion

Tags:

c++

pointers

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?

like image 933
a1337q Avatar asked Aug 03 '10 13:08

a1337q


People also ask

Does sizeof work on pointers?

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.

Why is pointer size 4 bytes?

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.

What is difference pointer and array?

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.

Why size of pointer is 8 bytes?

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.


2 Answers

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.
like image 110
James Curran Avatar answered Sep 28 '22 17:09

James Curran


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.

like image 27
Didier Trosset Avatar answered Sep 28 '22 17:09

Didier Trosset