8

If I enter the number 5, this loop has to run 5 times but it is running 6 times. What is the problem?

 int main(){
        int i, *arr, size;
        printf("Please enter the Number: ");
        scanf("%d ",&size);
        arr = (int*) malloc(size * sizeof(int));
        for(i = 0; i < size; i++){
            scanf("%d ", &arr[i]);
        }
 }
undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Murali krishna
  • 823
  • 1
  • 8
  • 23

3 Answers3

23

Remove the trailing space from the scanf() format string being used in the loop.

It causes scanf() to discard all whitespace after having read an int (%d), until it finds something that is not whitespace. On the fifth iteration of the loop, scanf() reads the int, and keeps going until it finds non-whitespace. This gives the illusion of needing to read one more integer.

On the last call of scanf(), any non-whitespace character after the integer data will cause reading to end.

Peter
  • 35,646
  • 4
  • 32
  • 74
7

Remove the space here:

This:

 scanf("%d ",&arr[i]);
          ^

should be:

 scanf("%d",&arr[i]);
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    Yes it is working. But what is the problem? – Murali krishna Mar 03 '16 at 09:04
  • 1
    It's related to [`scanf`](http://www.cplusplus.com/reference/cstdio/scanf/) which is quite complicated. Don't bother for the moment. – Jabberwocky Mar 03 '16 at 09:05
  • 1
    Please can you please give me the source so that i can go and read? I am curious to know about it.@Michael Walz – Murali krishna Mar 03 '16 at 09:07
  • 2
    @Muralikrishna A whitespace character in the format string of `*scanf` instructs `*scanf` to read and discard any number of whitespace characters, if any, **until the first non-whitespace character**. So, your `scanf`, after the fifth iteration, waits for a non-whitespace character, as the bolded part above says. – Spikatrix Mar 03 '16 at 09:10
  • 1
    @Muralikrishna click on "scanf" in my previous comment. This will open a page for the complete documentation of scanf. – Jabberwocky Mar 03 '16 at 09:27
0

I too faced the similar problem. To get it perfect please remove the space after %d in the loop. It should work. Might be some property of scanf.

int main(){
        int i, *arr, size;
        printf("Please enter the Number: ");
        scanf("%d",&size);// Note the change here
        arr= (int*) malloc(size * sizeof(int));
        for(i= 0;i < size;i++){ 
            scanf("%d",&arr[i]);
        }
    }
Anil Kumar
  • 348
  • 5
  • 16