C sizeof char指针
为什么这个char变量的大小等于1?
int main(){ char s1[] = "hello"; fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1 }
NOTA:原始问题起初有点变化: 为什么这个char指针的大小为1
sizeof(*s1)
是相同的
sizeof(s1[0])
,它是char
对象的大小,而不是char
指针的大小。
char
类型对象的大小始终为1
in C.
要获取char
指针的大小,请使用以下表达式: sizeof (&s1[0])
为什么这个char变量的大小等于1?
因为C标准的char
大小保证为1
字节。
*s1 == *(s1+0) == s1[0] == char
如果要获取字符指针的大小,则需要将字符指针传递给sizeof
:
sizeof(&s1[0]);
因为您正在引用从数组s1
衰减的指针,所以您获得第一个指向元素的值,即char
和sizeof(char) == 1
。
sizeof(*s1)
表示“ s1
指向的元素的大小”。 现在s1
是一个char
数组,当它被视为一个指针(它“衰变成一个指针”)时,取消引用它会产生一个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.