Search code examples
cdynamic-arrays

Input of multiple integers at once for dynamic array in C


My input consists of a sequence of integers, that need to be saved in a dynamic array. The number of integers is the first integer of the sequence. For example: 3 23 7 -12 or 5 -777 3 56 14 7

The sequence is ONE input.

How can i scan such an input?

For scanf("%i %i %i ...",)i need to know the amount of integers in advance, which i dont.


Solution

  • Use multiple scanf calls. First read the count, then read the values in a loop.

    int count;
    scanf("%i", &count);
    int values[count];
    for (int i=0; i<count; i++) {
        scanf("%i", &values[i]);
    }
    

    Note that this doesn't include error checking for invalid values.