问题
This might be trivial and I hope someone could explain this. Why strlen is giving me larger number than this real size of char array instead of 4: Here is my code:
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[4];
szInput [0] = '1';
szInput [1] = '1';
szInput [2] = '1';
szInput [3] = '1';
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
return 0;
}
I thought I should be getting 4 as the output but I am getting 6.
The sentence entered is 6 characters long.
回答1:
strlen
only works if a null terminator '\0'
is present in the array of characters. (It returns the number of characters up to but not including that terminator).
If not present then the program behaviour is undefined. The fact that you get an answer at all is entirely a coincidence.
If you had written szInput[3] = '\0';
then your program would be well-defined and the answer would be 3. You can write szInput[3] = 0;
but '\0'
is often preferred for clarity (and convention) when dealing with char
literals.
回答2:
You have to end your string with a '\0'
like this:
#include <stdio.h>
#include <string.h>
int main () {
char szInput[5];
szInput [0] = '1';
szInput [1] = '1';
szInput [2] = '1';
szInput [3] = '1';
szInput [4] = '\0';
printf ("The sentence entered is %u characters long.\n", (unsigned)strlen(szInput));
return 0;
}
回答3:
The missing '\0'
at the end of the string.
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[5];
szInput [0] = '1';
szInput [1] = '1';
szInput [2] = '1';
szInput [3] = '1';
szInput [4] = '\0';
printf ("The sentence entered is %u characters long.\n", (unsigned int)strlen(szInput));
return 0;
}
you should always add one extra character to your string to mark it's end, this extra special value is '\0'
.
All the functions in the string.h
header expect this, strlen()
works in a way which will cause undefined behavior in cause you omit the terminating '\0'
, a simple implementation would look like
size_t length;
while (*(str++) != '\0')
length++;
if the '\0'
is never found, this could read beyond bounds.
来源:https://stackoverflow.com/questions/28028448/strlen-gives-larger-number-than-the-size-of-an-array