Home > Mobile >  Size of array of pointers to char
Size of array of pointers to char

Time:11-24

I printed the size of this global variable and the output was 20. I'm trying to understand how it's not just 15 since there's 5 elements, each one is size of 3 (including the \0 at the end of each one).

#include <stdio.h>

char* arrChar[5] = { "hh","jj","kk","zz","xx" };

int main()
{
printf("size = %d\n", sizeof(arrChar));
}

I don't know if there's a connection but if we combined all the numbers here it would be 20, still I don't understand how the number of elements (5) added to the size of the elements in the array (15) is making any sense.

enter image description here

CodePudding user response:

You are correct that 15 bytes are occupied somewhere in memory. But that information is generally of no use.

For char str[] = "1"; , sizeof(str) is same as sizeof(char*), it's always the size of a pointer (4 bytes in your 32-bit settings)

For char str[] = "1234567"; sizeof(str) is still the same (use strlen for string's length)

If you have 5 strs then its size is 4 x 5.

You can use sizeof(arrChar)/sizeof(*arrChar) to get the total number of elements in the array.

CodePudding user response:

In your example the actual data are string literal stored in some read-only section of memory. The data isn't allocated inside arrChar, just the addresses to the data.

No matter what you set each pointer to point at, sizeof(arrChar) will always yield sizeof(char*) * 5. In case pointers are 4 bytes large, then 4*5=20.

CodePudding user response:

The *char pointer takes up 4 bits per element. Since there are 5 elements in your list, even normal char takes up 3 bits, but since your pointer occupies 4 bits, so it takes 20 bits, not 15.

  • Related