Perhaps a short example would help. Lets pretend that I wanted to read a file very similar to yours. I would do a few things:
I would need to declare storage space. An array is a perfectly good structure, but since we don't know how much items we will have, and because arrays aren't resizeable, we will have to simulate our array.
Simulating an array is something that a pointer is very good at doing. So to start with you will need to declare some space, perhaps
Code:
/** This function returns the result of a malloc call for an array of
** this_many floats. Not recommended for everyday use.
**/
float * make array ( int this_many )
{
float * acquired = malloc( sizeof *acquired * this_many );
return acquired;
}
And then you start reading your numbers until you're about to run out of array space. This is why it is important to keep track of the array size and why the size must not be constant: At that point, you're going to have to ask realloc to make a bigger array like
Code:
/**
** This function attempts to reallocate more space and points a pointer
** at it if possible. If allocation fails, the pointer and the size remain
** unchanged.
** If the received size (old_space) is <= zero, four items will be allocated.
** This function doesn't handle bad pointers with care.
**
** Returns the size of the array.
** Not recommended for everyday use.
**/
int dbl_space ( float ** that, const int old_space )
{
int amount = old_space > 0 ? old_space * 2 : 4;
/** Realloc needs two things to work, the old pointer and the new, expected size.
** Point a pointer to the data that realloc returns.
**/
float * acquired = realloc( *that, sizeof(float) * amount );
if ( acquired != NULL ) {
/** This way if it succeeds you can assign your new storage room without a
** much trouble.
**/
*that = acquired;
} else {
/** Or do whatever may be appropriate in the opposite case, like exiting. **/
return old_space;
}
return amount;
}
The only way you would successfully make an array bigger is if you knew what the old size was, because the new size you pass to realloc is a calculation that you would need to make.
Once you've finished reading from the file, it will be your responsibility to use the array properly. Then when you are done with the array, free( ) it so that you don't experience a memory leak. This is a very important step that people can forget to do. Memory leaks can result in overconsumption of your computer's memory due to the fact that the substantial space that the array took up won't be returned to the OS for recycling. This can have a lasting effect on the performance of the user's machine and force a reboot.
I may show my example program later, but hopefully you'll find a solution yourself now.