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?
Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.
Size of Character Pointer The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.
The pointer ptr, and all pointers, are 8 bytes, because they hold addresses, which are 8 bytes, or 64 bits. Assigning any address to an array variable is not allowed.
For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string.
firstname
is a char
array carrying a trailing 0
-terminator. lastname
is a pointer. On a 64bit system pointers are 8 byte wide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With