Reputation: 219
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.
Upvotes: 2
Views: 222
Reputation: 31599
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 str
s then its size is 4 x 5.
You can use sizeof(arrChar)/sizeof(*arrChar)
to get the total number of elements in the array.
Upvotes: 2
Reputation: 213306
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.
Upvotes: 1