Loading an array from a file presents an interesting dilemma. The problem resolves around how many elements you should plan for in the array. Let's say 100, but what if the file has fewer or more than 100 values. How can the program handle it correctly?
The solution involves some simple steps:
- We can read the file once to get the element count. Thus, we will know exactly how many members (elements) we will need.
- We can then create an array using dynamic memory allocation by defning the array within a function so that it has local scope. Local scope variables are created during the execution of the program and use the stack as the storage location instead of the data area. If you define the array outside of a function (global scope also known as static memory allocation) it stores it in the data area and must know how much storage space to allocate to the array when you write the source code. Since we don't know how many elements will be on the input file when we write the source code defning an array with global scope will not work. But, we can determine exactly how many members we need for the array by having our program count them (step 1) so that we can then define the array with local scope to the precise size needed.
- We can then load the array by reading the file a second time and storing the values read into the array just created.
This method is demonstrated in the demo file provided, thus you need to study this material in conjunction with the demo program.