printf("%lu \n", sizeof(*"327"));
我一直认为指针的大小在64位系统上是8个字节但是这个调用一直在返回1.有人可以提供解释吗?
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
.
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 .
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.