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