C sizeof char pointer

后端 未结 5 1003
感动是毒
感动是毒 2021-01-07 08:41

Why is size of this char variable equal 1?

int main(){

char s1[] = \"hello\";

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

}


        
相关标签:
5条回答
  • 2021-01-07 09:22
    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.
    
    0 讨论(0)
  • 2021-01-07 09:23

    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.

    0 讨论(0)
  • 2021-01-07 09:34

    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])

    0 讨论(0)
  • 2021-01-07 09:35

    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.

    0 讨论(0)
  • 2021-01-07 09:47

    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]);
    
    0 讨论(0)
提交回复
热议问题