Ilan Aizelman WS
Ilan Aizelman WS

Reputation: 1632

Getting a wrong output when printing a dynamic array

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

Upvotes: 1

Views: 36

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

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!

Upvotes: 4

Related Questions