Why is it that sizeof("Bill") is 5 but sizeof(char) is 1?
Shouldn't that make sizeof("Bill") be 4 since the length of the string is 4 chars (4 x 1)?
I believe it may have something to do with "Bill" being an array of characters, but why does that increase the byte size?
C strings are null terminated. There is a zero byte at the end of that string. Assuming ASCII, "Bill" looks like this in memory:
'B' 'i' 'l' 'l' '\0'
0x42 0x69 0x6c 0x6c 0x00
From the C standard, Section 6.4.5 String literals, paragraph 7:
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.
If you want to get an answer of 4 for the length, you should use strlen("Bill"), rather than sizeof.
If you really don't want the null-terminator, that's possible too, though probably ill-advised. This definition:
char bill[4] = "Bill";
will yield a 4-byte array bill containing just the characters 'B', 'i', 'l', and 'l', with no null-terminator.
it has a 0 as a terminator character, so its B i l l 0
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