Search code examples
arrayscpointersintegerscanf

How to enter integers into array with scanf?


int num = 0, k = 0;

scanf("%d %d", &num, &k);

int* A = #
    
for (int i = 0; i < num; i++)
{
    scanf("%d", &A[i]); //scanf("%d", A+i);
}

in that code, I want 4 5 1 3 2 integers put in the array A

input is

5 7
4 5 1 3 2

but in debug mode, there are

    *A  4           int
*(A+1)  5           int
*(A+2)  1           int
*(A+3)  3           int
*(A+4)  -858993460  int
*(A+5)  -858993460  int

why is the *(A+4) not 2??????

I tried the num+1, but that is not the ultimate solution.

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

Solution

  • To define an array, you'd do

    int A[num];
    

    Your variable A is a pointer to an integer, not an array. You can treat it as an array, as arrays are basically pointers in C. But the memory you're writing from scanf() is not 'allocated'.