Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8
Sizeof prints out 6 for:
printf("%d\n", sizeof("abcde"));
But it prints out 4 for:
char* str = "abcde";
printf("%d\n", sizeof(str));
Can someone explain why?
The string literal "abcde" is a character array. It is 6 bytes long, including the null terminator.
A variable of type char* is a pointer to a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes. sizeof is a compile time operation†, so it only looks at the variable's static type, which in this case is char*. It has no idea what's being pointed to.
† Except in the case of variable-length arrays, a feature introduced in the C99 language standard
First example, sizeof() return the length of the plain string.
Second example, sizeof() return the size of the pointer -> 32bits so 4 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With