Array Declaration
Arrays are like any other variable. They can contain any kind of data: primitives like integers, structs like point_2d
, or any other type you have created. You can declare them anywhere you declare a variable: as local variables, global variables, parameters, and as fields in structs and unions. In each case, you picture the array as containing a fixed number of places in which you can store a value of the indicated type. The following image shows a data
array that contains four integer values, and another points
array that contains three point_2d
values. The image also illustrates the idea of accepting arrays as parameters, using them in local variables, and as fields in your structs.
You should be able to picture arrays anywhere you have data within your program.
Arrays in C/C++
You can initialise an array when it is declared using a list of values in braces ({...}
). This can only be done to initialise arrays in the variable declaration, and is not valid elsewhere.
The size of the array must be able to be determined at compile time. If you initialise the array, you can leave the number of elements out of the array declaration (in the square brackets) as the compiler can work out the size from the number of elements you provide.
Example
The following example demonstrates the declaration of three arrays, value
, my_data
, and other
, each with five elements as well as a data
variable from a number_data
struct. The elements for data
and other
are initialised when the arrays are created, while values for my_data
are provided in the for loop.
The array in data
can contain a hundred values, but we can use num_values
to indicate we have only initialised the first three. Notice how we can then use num_values
in the loop to ensure we do not print values we have not initialised.
If you compile and run this program you will get something like the following. See how this only prints the first values from the data.value
array.