简体   繁体   中英

Char * Array Memory Allocation in C++

Lets say below is my char pointer array:

char *names[4] = {"abc", "def", "ghi", "jkl"};
for(int i = 0; i < 4; i++){
   cout << &names[i] << endl;
}

This will print 4 memory allocations:

0x7fff591c9b90
0x7fff591c9b98
0x7fff591c9ba0
0x7fff591c9ba8

My Question is why is it allocating 8 bytes for each element in the array? Can you help me in understanding how memory is allocated for each data type in C++? like for Char *, char, in, int *, string, etc., or quote any reference.

TIA

My Question is why is it allocating 8 bytes for each element in the array?

Well probably because size of pointer on your machine is 8 bytes. It is common that size of pointer is 8 bytes on 64 bit systems. But again there is no hard rule for this and size of pointers may vary per machine. And since each element of your array is a pointer, hence the result.

Memory allocation say for int is different from int* in that in the former you need to allocate space which will hold all values of integer, while in the latter, you need as much space to contain value of a pointer.

A string literal is an array of read-only char elements, terminated by the special character '\\0' . When you use a string literal it decays to a pointer to the first element in that array. So making an array of four pointers to char will always have the element size be the size of a pointer, even if that pointer is to a string literal.

On 64 bit systems the usual size of a pointer is 64 bits, ie 8 bytes. That's why each element in the array is 8 bytes. On a 32 bit system, the size of pointers are of course 32 bits, 4 bytes.

The length of the string literals doesn't matter, for example take

char const* string_array[] = { "a", "bc", "def", "ghij" };

In the above array the element size will still be the size of the pointer, ie 8 bytes on a 64 bit system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM