1

I'm trying to input an array length from user, and the output the numbers..

I get only "1", "1", "1" as output when n = 3, and num's values are integers.

int main()
{
    int *arr1, n,num = 0,*p;
    printf("Please enter the size of the array: ");
    scanf("%d", &n);
    arr1 = (int*)malloc(n * sizeof(int));
    if (arr1 == NULL)
        printf("Not enough memory\n");
    else  printf("Array was allocated!\n" );
    for (p = arr1; p < arr1 + n; p++)
    {
        *p = scanf("%d", &num);
        printf("%d ", *p);
    }

    free(arr1);
    getch();
}
3
  • 1
    You use scanf correctly one time, why not the second? Commented Dec 26, 2015 at 17:27
  • @JoachimPileborg Damn good question. Commented Dec 26, 2015 at 17:28
  • 1
    For future reference, when posting a question regarding unexpected output, besides telling us the actual output also include the expected output, as well as the input. Please read about how to ask good questions. Commented Dec 26, 2015 at 17:32

1 Answer 1

4

scanf returns the number of matches. num contains the entered integer.
From man scanf:

Return Value

These functions return the number of input items successfully matched and assigned [...]

Replace

*p = scanf("%d", &num);

with

scanf("%d", &num);
*p = num;

or simply1

scanf("%d", p);

to make it work properly.


1 Thanks to @JoachimPileborg!

Sign up to request clarification or add additional context in comments.

5 Comments

Or simply scanf("%d", p);
Why while (arr1 < arr1 +n) { scanf("%d", arr1); } doesn't work? @JoachimPileborg
@IlanAizelmanWS That code will work very well, if you want an infinite loop. You don't increase an1 anywhere in the loop.
@JoachimPileborg Still does not work. while (arr1 < arr1 + n) { scanf("%d", arr1); arr1++; } It just continues asking for more input.
@IlanAizelmanWS because arr1 will ALWAYS be lesser than arr1 + n. Note that as arr1 increases, so does arr1 + n. You need a limit that is independent of arr1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.