size of character array and size of character pointer
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?
Solution 1:
firstname
is a char
array carrying a trailing 0
-terminator. lastname
is a pointer. On a 64bit system pointers are 8 byte wide.
Solution 2:
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.