为什么这个 char 变量的大小等于 1?
int main(){
char s1[] = "hello";
fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1
}
注意:最初的问题有一点改变:为什么这个 char 指针的大小是 1
sizeof(*s1)
是相同的
sizeof(s1[0])这是char对象的大小,而不是char指针的大小。
类型对象的大小char始终1在 C 中。
要获取char指针的大小,请使用以下表达式:sizeof (&s1[0])
为什么这个 char 变量的大小等于 1?
因为C 标准char保证 a 的大小是1字节。
*s1 == *(s1+0) == s1[0] == char
如果要获取字符指针的大小,则需要将字符指针传递给sizeof:
sizeof(&s1[0]);
因为您正在推迟从数组中衰减的指针,s1所以您获得了第一个指向元素的值,即 achar和sizeof(char) == 1。
sizeof(*s1)表示“由”指向的元素的大小s1。Nows1是一个chars 的数组,当被视为一个指针时(它“衰减”为一个指针),取消引用它会产生一个 type 的值char。
而且,永远sizeof(char)是一个。C标准要求它是这样的。
如果您想要整个数组的大小,请sizeof(s1)改用。
sizeof(*s1) means its denotes the size of data types which used. In C there are 1 byte used by character data type that means sizeof(*s1) it directly noticing to the character which consumed only 1 byte.
If there are any other data type used then the **sizeof(*data type)** will be changed according to type.