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?
sizeof
andstrlen()
give a result of typesize_t
. Use%zu
, not%lu
to printsize_t
values. Or, if your compiler doesn't support%zu
, convert to a known type and use the appropriate format for that type. – Alas