size of character array and size of character poin

2019-01-07 20:00发布

I have a piece of C code and I don't understand how the sizeof(...) function works:

#include <stdio.h>

int main(){
   const char  firstname[] = "bobby";
   const char* lastname = "eraserhead";
   printf("%lu\n", sizeof(firstname) + sizeof(lastname));
   return 0;
}

In the above code sizeof(firstname) is 6 and sizeof(lastname) is 8.

But bobby is 5 characters wide and eraserhead is 11 wide. I expect 16.

Why is sizeof behaving differently for the character array and pointer to character?

Can any one clarify?

标签: c char sizeof
5条回答
时光不老,我们不散
2楼-- · 2019-01-07 20:06

The size of your first array is the size of bobby\0. \0 is the terminator character, so it is 6.

The second size is the size of a pointer, which is 8 byte in your 64bit system. Its size doesn't depends on the assigned string's length.

查看更多
戒情不戒烟
3楼-- · 2019-01-07 20:11

firstname is an array of 6 chars, including the terminating '\0' character at the end of the string. That's why sizeof firstname is 6.

lastname is a pointer to char, and will have whatever size such a pointer has on your system. Typical values are 4 and 8. The size of lastname will be the same no matter what it is pointing to (or even if it is pointing to nothing at all).

查看更多
Summer. ? 凉城
4楼-- · 2019-01-07 20:12

sizeof an array is the size of the total array, in the case of "bobby", it's 5 characters and one trailing \0 which equals 6.

sizeof a pointer is the size of the pointer, which is normally 4 bytes in 32-bit machine and 8 bytes in 64-bit machine.

查看更多
贪生不怕死
5楼-- · 2019-01-07 20:17

firstname[] is null-terminated, which adds 1 to the length.

sizeof(lastname) is giving the size of the pointer instead of the actual value.

查看更多
别忘想泡老子
6楼-- · 2019-01-07 20:23

firstname is a char array carrying a trailing 0-terminator. lastname is a pointer. On a 64bit system pointers are 8 byte wide.

查看更多
登录 后发表回答