I assign the same string value to a pointer and a char
array
char *str = "hello" "world";
char str1[] = "hello" "world";
Then use sizeof()
function to return their lengths
sizeof(str); // on my computer, it's 8 !!
sizeof(str1); // return 11, which is right
But both of them can be printed out right by %s
:
printf("%s\n%s\n", str, str1);
So why does sizeof(str);
return a wrong value ?
So why does sizeof(str);return a wrong value ?
It does not because sizeof
returns the size in bytes of the type of its operand. From section 6.5.3.4 The sizeof operator of the C99 standard (draft n869), clause 2:
The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
Therefore:
sizeof(str) == sizeof(char*)
sizeof(str1) == sizeof(char[11])