Reputation: 67
char msg[100] = {’C’,’P’,’R’,‘E’,‘\0’,‘2’,‘8’, ‘8’,‘\0’};
int my_length = 0xFFFFFFFF;
my_length = strlen(msg);
I thought it is nine, however, the answer is 4. anyone can explain? thanks
Upvotes: 0
Views: 209
Reputation: 123578
Remember that in C, a string is simply a sequence of character values followed by a zero-valued terminator. Strings are stored in arrays of char
(or wchar_t
for wide strings), but not every array of char
(or wchar_t
) is a string. To store a string that's N
characters long, you need an array with at least N + 1
elements to account for the terminator.
strlen
returns the number of characters in the string starting at the specified address up to the zero terminator.
To get the size (in bytes) of the msg
array, use the sizeof
operator:
char msg[100] = {'C','P','R','E','\0','2','8','8','\0'};
size_t my_length = strlen( msg );
size_t my_size = sizeof msg;
if ( my_length >= my_size )
// whoopsie
In this case, you're actually storing two strings in one array ("CPRE"
and "288"
).
The size of the msg
array is 100 (as given by the declaration).
The length of the string "CPRE"
starting at msg[0]
is 4, since you have a zero terminator in the fifth element of the array ('\0' == 0
).
The length of the string "288"
starting at msg[5]
is 3 since you have another zero terminator in the ninth element of the array.
Upvotes: 2
Reputation: 21572
You cannot assume that the return value of strlen
represents the size of an array.
strlen
will take a pointer to the start of a string and increment the pointer while looking for a null terminator; once it finds that, it returns the counter (i.e. number of increments before the null was found).
You declared msg
to be of length 100, but only populated 9 elements in the array. sizeof(msg)
will be 100.
Are you actually asking "how can I find out how many values are initialized in an array"? There's really no answer to that.
Upvotes: 1
Reputation: 8053
strlen
returns 4 because the (first) string in msg
is terminated by the \0
at msg[4]
. However, the array msg
has a length of 100 char
s because it was declared as such.
Upvotes: 4
Reputation: 14191
Maybe it is typo in your
char msg[100] = {’C’,’P’,’R’,‘E’,‘\0’,‘2’,‘8’, ‘8’,‘\0’};
and you wanted
char msg[100] = {’C’,’P’,’R’,‘E’,‘0’,‘2’,‘8’, ‘8’,‘\0’};
(plainly: CPRE0288
), so binary 0
(instead of the character representation of 0 , i. e. '0'
) prematurely finishes your string.
Upvotes: 1
Reputation: 245479
strlen
will stop counting as soon as it hits a null terminator (as C uses null terminated strings and expects to only find them at the end of a string).
You have four characters before your first null terminator, therefore the length is 4.
Upvotes: 4