Does Loop work more than specified in C? What for?

If I enter the number 5, this loop should run 5 times, but it works 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]); } } 
+8
c loops scanf
source share
3 answers

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

This causes scanf () to discard all spaces after reading int ( %d ) until it finds something that is not a space. At the fifth iteration of the loop, scanf() reads int and continues moving until it finds spaces without spaces. This gives the illusion of having to read another integer.

The last time scanf() called, any character without a space after the whole data will finish reading.

+23
source share

Remove the space here:

It:

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

it should be:

  scanf("%d",&arr[i]); 
+7
source share

I also ran into a similar problem. To do this, please remove the space after % d in the loop. It should work. Maybe some kind of scanf property.

 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]); } } 
0
source share

All Articles