Sizes of arrays declared with pointers

后端 未结 5 1773
走了就别回头了
走了就别回头了 2021-01-23 14:24
char c[] = \"Hello\";
char *p = \"Hello\";

printf(\"%i\", sizeof(c)); \\\\Prints 6
printf(\"%i\", sizeof(p)); \\\\Prints 4

My question is:

Why

5条回答
  •  Happy的楠姐
    2021-01-23 14:45

    The two operands to sizeof have different types. One is an array of char, the other a pointer to char.

    The C standard says that when the sizeof operator is applied to an array, the result is the total number of bytes in the array. c is an array of six char including the NUL terminator, and the size of char is defined to be 1, so sizeof (c) is 6.

    The size of a pointer, however, is implementation-dependent. p is a pointer to char. On your system, the size of pointer to char happens to be 4 bytes. So that's what you see with sizeof (p).

    If you try sizeof(*p) and sizeof(*c), however, they will both evaluate to 1, because the dereferenced pointer and the first element of the array are both of type char.

提交回复
热议问题