Hi, I'm quite confused by a part of this code, hope someone can explain to me.
[HIGHLIGHT="C"]
int main() {
char buffer[128];
char *result;
while (!feof(stdin)) {
result = fgets( &buffer[0],128,stdin);
if (result!=NULL) {
buffer[strlen(buffer)-1] = '\0';
printf( "String is >%s<\n",&buffer[0]);
}
}
return 0;
}
[/HIGHLIGHT]
I would like to ask what does strlen(buffer) function do?
'\0' is supposed to eliminate the last character in the string right? Does it means if my string consist of 128 characters, it will remove the last character which means they will display 127 characters of string?
Can I safely conclude that the size of the largest string I can safety type into the program when it runs is 127?
Hope to see some clarification. Thanks in advance!
Explanation on strlen(buffer)
Started by littlevamp, Sep 14 2007 09:55 PM
1 reply to this topic
#1
Posted 14 September 2007 - 09:55 PM
|
|
|
#2
Posted 15 September 2007 - 05:45 AM
No, '\0' do not eliminate the last character in the string. It's the terminating NULL byte. It's the end-character for a string.
What strlen does is counting bytes in the string. It loops through the string, while counting, until it reaches a terminating NULL byte. Even if there's characters after the terminating NULL byte it will not continue.
It's easy to make a function yourself which does the job. This is just my version. IMO, simple and clean.
What strlen does is counting bytes in the string. It loops through the string, while counting, until it reaches a terminating NULL byte. Even if there's characters after the terminating NULL byte it will not continue.
It's easy to make a function yourself which does the job. This is just my version. IMO, simple and clean.
unsigned int my_strlen(const char *szString)
{
unsigned int iBytes = 0;
while(*szString++ != '\0')
iBytes++;
return iBytes;
}
And you can test it...
char buffer[128];
printf("sizeof: %u\n", sizeof(buffer));
printf("strlen: %u\n", strlen(buffer));
printf("my_strlen: %u\n", my_strlen(buffer));
buffer[0] = 'a';
buffer[1] = '\0';
buffer[2] = 'b';
printf("sizeof: %u\n", sizeof(buffer));
printf("strlen: %u\n", strlen(buffer));
printf("my_strlen: %u\n", my_strlen(buffer));


Sign In
Create Account

Back to top









