I am trying to understand why this printf
statement gives two different outputs; I think I have a decent understanding of one of the outputs.
Here is the code:
const char *ptr = "hello";
const char array[] = "hello";
//Question 2
printf("%zu %zu\n", sizeof(ptr),sizeof(array));
Now I understand why sizeof(array)
returns six: this is because the length of "hello"
is 6 plus an additional null terminator.
But I do not understand why sizeof(ptr)
is 8; my guess is that all memory addresses in C occupy 8 bits of memory hence the size is 8. Is this correct?
>Solution :
The C language, itself, doesn’t define what size a pointer is, or even if all pointers are the same size. But, yes, on your platform, the size of a char*
pointer is 8 bytes.
This is typical on 64-bit platforms (the name implies 64-bit addressing which, with 8 bits per byte, is 64/8 = 8 bytes). For example, when compiling for a Windows 64-bit target architecture, sizeof(char*)
is 8 bytes; however, when targeting the Windows 32-bit platform, sizeof(char*)
will be 4 bytes.
Note also that the "hello"
string literal/array is 6 bytes including the nul
terminator.