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衰减的指针,所以您获得第一个指向元素的值,即charsizeof(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.