The main issue here is to create an array wide enough to store all the integers contained in the standard input, but we don't know how many values we are going to read.
The input is a file on the Hard Disk Drive
If you read from a file, you can afford to read the file twice: the first time, you do not store the values, you just count how many values there are; the second time, you allocate an array with the right size with malloc() and you store the integers into the array.
The input is read from the standard input
On the other hand, if you read from the standard input, you can't read the input twice, because it is consumed as soon as you read it. So you need to compute the size of the array and store the elements in the array at the same time. To do this, you begin by allocating an array of size 10, then you read 10 values from the standard input, and if the array is not big enough, you allocate another one bigger, you copy the values read so far from the first array into the second array, you delete the first array, and you continue to do this until all the input is exhausted.
Here is the algorithm:
- Allocate an array of 10 integers with
malloc().
- Read integers from the standard input with
scanf() until the end of the input or until the array is full.
- If there are no more integers to read from the standard input, stop.
- Otherwise, use the function
realloc() to double the size of the array, and go back to step 2. The realloc() function will potentially allocate a second array with the new size, copy the integers from the first array into the first half of the second array (this will happen if there is not enough free space after the end of the first array to expand it).
If it is too difficult
It is not a one-liner like in Python. Doing this correctly is actually quite hard for a beginner. If you struggle too much, just dump the standard input into a temporary file on the hard disk drive, and use the trick of reading the file twice.
If the input is produced by something you control, you could also try to change the format of the input. For instance, if you add the number of values that need to be read as the first element of the input, it will simplify your task.
listis fostering a whole generation of confused programmers. Shame on GVR.