Why does sizeof(*“327”) return 1 instead of 8 on a 64 bit system?

与世无争的帅哥 提交于 2019-12-03 09:43:47

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.

Marievi

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.

CiaPan

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.

msc

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!