1
int *ptr = (int *) malloc(n*sizeof(int));
  
  if(!ptr) exit(0);

  for(int i=0;i<n;i++)
{   
  scanf("%d ",&ptr[i]);
}

Recently I learned about working scanf where it was mentioned that if there is a space after the format specifier then it just reads the space or any new line character and discards it. But in the above code when the value of n is 3 ,it takes input 4 times and expected values are assigned to the indices of ptr.Can someone please explain why scanf takes input 4 times when there is a space after "%d".

Here's the complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
   int n;
   printf("Enter the number of terms\n");
   scanf("%d",&n);
   int *ptr = (int *) malloc(n*sizeof(int));
   
   if(!ptr) exit(0);

   for(int i=0;i<n;i++)
 {   
   scanf("%d ",&ptr[i]);
 }
  printf("The entered numbers are:\n");
   for(int i=0;i<n;i++)
 {
  printf("%d ",ptr[i]);
 }
Aditya
  • 13
  • 2
  • What makes you think `scanf` is being called 4 times in the loop if `n` is equal to 3? It's not. You loop 3 times. `scanf` is invoked 3 times. It reads 3 values and stores them in the array you allocated. End of story. – paddy Nov 08 '21 at 03:01
  • 1
    A space in the scanf string means to read **any amount of** whitespace and discard it. Not 1 character as you seem to describe. So this means that it will keep reading until you enter some non-whitespace characters (otherwise it would not yet know that all the whitespace has been read) . Generally speaking this is not desirable behaviour so you should avoid putting a space at the end of a scanf format string – M.M Nov 08 '21 at 03:19

0 Answers0