Jump to content

Explanation on strlen(buffer)

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
littlevamp

littlevamp

    Newbie

  • Members
  • Pip
  • 5 posts
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!

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
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.
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));