1

In my program, after I enter the first input. I expected the values to get printed because of the printf statement next to scanf, but for the first time alone it's not getting printed.For the next iterations and all its working correctly

Ex:

Output :
Enter input10
12
i=0,a[i]=11896224
Enter input

Code:

#include<stdio.h>
#include<stdlib.h>
int func(int *, int);
int *a;
int main()
{
    int length = 5;
    a = (int *)malloc(sizeof(int)*length);
    for (int i = 0;i < length;i++)
    {
        printf("Enter input");
        scanf("%d\n", &a[i]);//100,104,108,112,116
        printf("i=%d,a[i]=%d\n", i, &a[i]);/*Print Statement which is not executing for first time*/
    }
    func(a, length);
    return 0;
}

int func(int *b, int length)
{
    printf("Length=%d", length);
    for (int j = 0;j < length;j++)
        printf("b[%d]=%d", j, b[j]);//
    return 0;
}
VijayManohar7
  • 113
  • 1
  • 10
  • I think you'll find that scanf doesn't do what you think it does. – Jasen Sep 02 '15 at 02:10
  • possible duplicate of [Weird scanf behaviour when reading number and newline](http://stackoverflow.com/questions/21828797/weird-scanf-behaviour-when-reading-number-and-newline) – smac89 Sep 02 '15 at 03:07
  • Side notes: (1) [Don't cast the result of `malloc()`](http://stackoverflow.com/q/605845/3488231), and (2) It may be preferable to use [`size_t`](http://stackoverflow.com/q/2550774/3488231) or `ssize_t` for lengths. – user12205 Sep 02 '15 at 03:09
  • @Smac89 its a bit similar but not exactly the same,For me only for the first iteration the problem occurs ,for the remaining trials its working fine – VijayManohar7 Sep 02 '15 at 18:29

1 Answers1

1

Remove the \n from the scanf function.

powersource97
  • 305
  • 4
  • 12
  • @Daniel Fischer ,I found your article in the following url "http://stackoverflow.com/questions/15443483/using-n-in-scanf-in-c", Can you suggest the reason for this problem – VijayManohar7 Sep 02 '15 at 18:21
  • I am not entirely sure, but it has something to do with whitespaces in the buffer, which is ignored by `scanf` or something as such. – powersource97 Sep 02 '15 at 18:38