Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a string's byte size longer than the length? [closed]

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?

like image 548
Danny Garcia Avatar asked Jun 03 '13 21:06

Danny Garcia


2 Answers

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.

like image 120
Carl Norum Avatar answered Oct 14 '22 07:10

Carl Norum


it has a 0 as a terminator character, so its B i l l 0

like image 26
Keith Nicholas Avatar answered Oct 14 '22 08:10

Keith Nicholas