Search code examples
carraysinputstdio

Input a dynamic length array in C using scanf


I have to input an array of integers. The length of this array is determined at runtime when the user hits some sentinal key (likely I'll use return)

EXAMPLE

//input path to be analyzed
  int n = 0;
  while(scanf("%d",&input[n])==1){
    //??
  }
}

Input:

3 2 1 3 4 5 (return)

Then these values are stored in the array a as:

[3, 2, 1, 3, 4, 5]

I also need proper error checking of course.

This is a basic problem im sure however I'm unable to solve it.

Thanks!

Im thinking ill need a while loop however im unsure how to use scanf to both terminate the loop, initilize the array and input the values.


Solution

  • You can do it as follows:

    int main()
    {
        char ch;
        int i=0;
        int input[100000]; //Or dynamically allocate
        while(scanf("%c",&ch) && (ch!='\n')){
        if(ch==' ') continue;
        input[i++]=ch - '0';
        printf("%d ",input[(i-1)]);
    }
    }