C sizeof char pointer

孤街醉人 提交于 2019-11-30 20:49:15

问题


Why is size of this char variable equal 1?

int main(){

char s1[] = "hello";

fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) )    // prints out 1

}

回答1:


NOTA: the original question has changed a little bit at first it was: why is the size of this char pointer 1

sizeof(*s1)

is the same as

sizeof(s1[0]) which is the size of a char object and not the size of a char pointer.

The size of an object of type char is always 1 in C.

To get the size of the char pointer use this expression: sizeof (&s1[0])




回答2:


Why is size of this char variable equal 1?

Because size of a char is guaranteed to be 1 byte by the C standard.

*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(&s1[0]);



回答3:


Because you are deferencing the pointer decayed from the array s1 so you obtain the value of the first pointed element, which is a char and sizeof(char) == 1.




回答4:


sizeof(*s1) means "the size of the element pointed to by s1". Now s1 is an array of chars, and when treated as a pointer (it "decays into" a pointer), dereferencing it results in a value of type char.

And, sizeof(char) is always one. The C standard requires it to be so.

If you want the size of the whole array, use sizeof(s1) instead.




回答5:


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.


来源:https://stackoverflow.com/questions/14295426/c-sizeof-char-pointer

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