Collections in C and C++ - arrays, vectors and heap memory blocks
Archive - Originally posted on "The Horse's Mouth" - 2011-04-12 12:20:33 - Graham EllisIf you want to hold multiple values within a table in a program, you'll want to use some form of collection or table - and in many languages including C++ and C, the most straightforward type of collection is an array. An array occupies sequential locations in the computer's memory when your program runs, and you can refer to individual values within it using either a positions number in square brackets, or by offsetting the address. I'll show you each of those, but let's start off by defining an array:
float rain[31];
rain is to be an array that holds up to 31 values (position numbers 0 to 30), each of which is a floating point number. From the name and size chosen in the example, it's probably fair to assume that in this example we're going to be storing the rainfall (in mm perhaps) for each day of the month.
We can the store values into individual elements of the array by their position number:
float temp;
int dayno;
for (dayno=0; dayno<31; dayno++)
{
scanf("%f",&temp);
rain[dayno] = temp;
}
And we can then access each of those values as may times as we like - here's an example of a loop that reads all through those values and comes up with a total monthly rainfall:
float totalRainfall;
totalRainfall = 0.0;
for (dayno=0; dayno<31; dayno++)
{
totalRainfall += rain[dayno];
}
There's a complete example (from which those code snippets are taken) [here]. Rather than type in 31 values every time I read the program, I redirected input from a data file and there's a sample data file [here].
Not all months have 31 days ... and indeed you'll very often have applications in which you don't even know a maximum array size when you compile. The standard library (stdlib.h) in C includes functions to let you allocate memory as you run the program - malloc and calloc let you select an amount of memory of your choice, and realloc even lets you change the amount of memory you need during a run. In C++, a vector provides a neat and easier to use wrapper around functions such as calloc, allowing true, easy(ish) dynamic programming.
There's an example that uses calloc as a comparison to the example above - it's [here]. And there's a first example with vectors / C++ [here].