C语言 C sizeof char 指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14295426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C sizeof char pointer
提问by user1477955
Why is size of this char variable equal 1?
为什么这个 char 变量的大小等于 1?
int main(){
char s1[] = "hello";
fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1
}
回答by ouah
NOTA: the original question has changed a little bit at first it was: why is the size of this char pointer 1
注意:最初的问题有所改变,它是:为什么这个字符指针的大小为 1
sizeof(*s1)
sizeof(*s1)
is the same as
是相同的
sizeof(s1[0])which is the size of a charobject and not the size of a charpointer.
sizeof(s1[0])这是char对象的大小而不是char指针的大小。
The size of an object of type charis always 1in C.
类型对象的大小char总是1在 C 中。
To get the size of the charpointer use this expression: sizeof (&s1[0])
要获取char指针的大小,请使用以下表达式:sizeof (&s1[0])
回答by Alok Save
Why is size of this char variable equal 1?
为什么这个 char 变量的大小等于 1?
Because size of a charis guaranteed to be 1byte by the C standard.
因为C 标准char保证a 的大小为1字节。
*s1 == *(s1+0) == s1[0] == char
If you want to get size of a character pointer, you need to pass a character pointer to sizeof:
如果要获取字符指针的大小,则需要将字符指针传递给sizeof:
sizeof(&s1[0]);
回答by Hyman
Because you are deferencing the pointer decayed from the array s1so you obtain the value of the first pointed element, which is a charand sizeof(char) == 1.
因为您正在推迟从数组衰减的指针,s1所以您获得第一个指向元素的值,即 a charand sizeof(char) == 1。
回答by Hyman
sizeof(*s1)means "the size of the element pointed to by s1". Now s1is an array of chars, and when treated as a pointer (it "decays into" a pointer), dereferencing it results in a value of type char.
sizeof(*s1)表示“由s1”指向的元素的大小。现在s1是一个chars数组,当被视为一个指针时(它“衰减为”一个指针),取消引用它会产生一个 type 值char。
And, sizeof(char)is always one.The C standard requires it to be so.
而且,永远sizeof(char)是一。C 标准要求它如此。
If you want the size of the whole array, use sizeof(s1)instead.
如果您想要整个数组的大小,请sizeof(s1)改用。
回答by Varun Chhangani
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.

