Reputation: 321
printf("%lu \n", sizeof(*"327"));
I always thought that size of a pointer was 8 bytes on a 64 bit system but this call keeps returning 1. Can someone provide an explanation?
Upvotes: 22
Views: 4757
Reputation: 106042
Putting *
before a string literal will dereference the literal (as string literal are array of characters and will decay to pointer to its first element in this context). The statement
printf("%zu \n", sizeof(*"327"));
is equivalent to
printf("%zu \n", sizeof("327"[0]));
"327"[0]
will give the first element of the string literal "327"
, which is character '3'
. Type of "327"
, after decay, is of char *
and after dereferencing it will give a value of type char
and ultimately sizeof(char)
is 1
.
Upvotes: 61
Reputation: 5009
The statement:
printf("%lu \n", sizeof(*"327"));
actually prints the size of a char
, as using *
dereferences the first character of string 327
. Change it to:
char* str = "327";
printf("%zu \n", sizeof(str));
Note that we need to use %zu
here, instead of %lu
, because we are printing a size_t
value.
Upvotes: 18
Reputation: 9570
The string literal is an anonymous, static array of chars, which decays to a pointer to its first character -- that is, a pointer value of type char *
.
As a result expression like *"abc"
is equivalent to *someArrayOfCharName
, which in turn is equivalent to *&firstCharInArray
which results in firstCharInArray
. And sizeof(firstCharInArray)
is sizeof(char)
which is 1
.
Upvotes: 4
Reputation: 34608
Good answer by haccks.
Also, the behaviour of your code is undefined, because you have used the wrong format specifier.
So, use %zu
instead of %lu
because sizeof()
returns size_t
and size_t
is unsigned
.
C11 Standard: §7.21.6.1: Paragraph 9:
If a conversion specification is invalid, the behavior is undefined.225) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
Upvotes: 0