Why does sizeof return different values for same string in C? [duplicate]

試著忘記壹切 提交于 2019-11-28 06:04:29

问题


Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8

Sizeof prints out 6 for:

printf("%d\n", sizeof("abcde"));

But it prints out 4 for:

char* str = "abcde";
printf("%d\n", sizeof(str));

Can someone explain why?


回答1:


The string literal "abcde" is a character array. It is 6 bytes long, including the null terminator.

A variable of type char* is a pointer to a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes. sizeof is a compile time operation, so it only looks at the variable's static type, which in this case is char*. It has no idea what's being pointed to.

† Except in the case of variable-length arrays, a feature introduced in the C99 language standard




回答2:


First example, sizeof() return the length of the plain string.
Second example, sizeof() return the size of the pointer -> 32bits so 4 bytes.




回答3:


Because here

printf("%d\n", sizeof("abcde"));

is a string, with considering NULL its 6 byte long.

and

char* str = "abcde";
printf("%d\n", sizeof(str));

is a pointer that requires 32bits hence 4 bytes :-)



来源:https://stackoverflow.com/questions/9644267/why-does-sizeof-return-different-values-for-same-string-in-c

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