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

假装没事ソ 提交于 2019-12-09 07:46:38

问题


 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?


回答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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/46705264/why-does-sizeof327-return-1-instead-of-8-on-a-64-bit-system

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