C pointer problem!
Why does the following C code does not ouput 10
#include<stdio.h>
#include开发者_StackOverflow<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}
void get_length(char *s){
int count;
for(count = 0 ; *s != '\0' ; s++)
count++;
printf("count = %d\n",count);
}
The input is I am Rohit
The output is count = 432 Can anyone please explain that.You appear to have a 5
instead of a %
in your scanf
format string. (Perhaps your keyboard's shift key needs cleaning.)
That means that scanf
isn't actually reading anything into your buffer. Your code doesn't check the return value from scanf
(it should!) and therefore never notices that it failed. So you're then trying to calculate the length of ... a buffer full of uninitialized junk. It could give you 432, or 0, or anything else at all.
[EDITED to add:] ... Oh. And even if you fix that, it still won't work because scanf
will stop reading when it sees a whitespace character, including a newline, and therefore the \n
your get_length
function is looking for will not be in the buffer.
Incidentally, do you know about the strlen
function in the C standard library?
I think you meant %s
, not 5s
.
BTW, value-initialising your array (char buff[128] = {}
) will prevent your array from being unbounded (count = 432
is arbitrary for you).
You should then check for *s != '\0'
, not \n
, in get_length
— C-style strings are bounded by the NULL character (\0
), not newlines, regardless that you took the data from user input. The newline is lost from that input.
I think that scanf is reading your string in and setting the last char to '\0', but you are searching for '\n', which I don't think is implicit in the scanf implementation.
That is, check for '\0' instead of '\n'.
The scanf
call is failing because you have used an invalid format. If you want a string of length 5, then the format should be "%5s"
instead of "5s"
, or just "%s"
if the five is a complete typo. So, the character buffer is uninitialized and you are getting the number of bytes before the first random '\n'
character is encountered on the stack. Also, scanf
ignores newline characters. So, your get_length
function will never work as expected.
精彩评论