Reputation: 279
#include <stdio.h>
int main()
{
int x=getlength("Hello",10);
printf("%d",x);
}
int getlength(char line[],int limit)
{
int x;
for(x=0;x<limit-1 && line[x]!=EOF && line[x]!='\n';++x)
printf("%c",line[x]) ;
printf("\n");
return x;
}
So this code seems to output this: Hello%d then it outputs on a new line 9
What I don't understand is where the %d came from and how length of Hello%d is equal to 9
If anyone can explain I'd be happy.
Upvotes: 2
Views: 158
Reputation: 6762
Try testing the NUL character value:
int getlength(char line[],int limit)
{
int x;
for(x=0;x<limit-1 && line[x]!='\n' && line[x]!='\0'; ++x)
{
printf("%c",line[x]) ;
}
printf("\n");
return x;
}
Upvotes: 0
Reputation: 48290
A character string in C is terminated with a null character, '\0'
. Change your for
loop to test for the null character instead of EOF
:
for (x=0; x < limit - 1 && line[x] != '\0' && line[x] != '\n'; ++x)
A function uses the constant EOF
to signal the end of a file, but it's not used to terminate strings. That's because binary files can contain (unsigned) characters with values from 0 to 255. In order for a function to signal end-of-file, it must return a value that cannot appear within the file. Every implementation I've seen uses EOF
= -1, because unsigned characters can never be negative.
A string, on the other hand, can only contain valid (unsigned) characters, so it can't use EOF
to mark its end. Instead, it uses '\0'
, which is equivalent to the integer 0 and is a vailid—but unprintable—character.
A very common pitfall for programmers is to forget this, and either neglect to terminate a string with a null character (in which case a program will often scan past the end into invalid memory), or to try to manipulate strings that contain binary data (which sometimes includes a null character and terminates the string unexpectedly).
Upvotes: 1
Reputation: 310
The length of 'Hello' is 5. My hunch is you are reading those characters from the stack frame. You are reading from location even after 'hello' on the stack. This is what is there on the stack. Probably from the '%d' in the printf.
Upvotes: 0
Reputation:
You for
loop just counts to 9 as it never finds a EOF or a newline in the string "Hello".
The string "Hello" is terminated with a null character '\0'
, so change a part of for loop to line[x]!='\0'
Upvotes: 0