A variable array is a group of variables stored under the same name but with different index values. In the array declaration and initialization example below, you can think of the index value as the position of a specific variable in the list.
int p[] = {1, 2, 3, 5, 7, 11};
Each array element has a name (which is p in this example, the same as the array name) and an index (between brackets) that makes it possible to select an element.
This declaration sets aside six variables, each storing a prime number. This array has been initialized so that the p[0] array element stores 1. Likewise, the p[1] element stores 2. It continues for the rest of the array elements: p[2] stores 3, p[3] stores 5, p[4] stores 7, and p[5] stores 11.
/* Array Variables.c Declare and initialize an array and display a couple of its elements. */ #include "simpletools.h" // Include simpletools int main() // main function { int p[] = {1, 2, 3, 5, 7, 11}; // Initialize the array print("p[0] = %d\n", p[0]); // Display what p[0] stores print("p[3] = %d\n", p[3]); // Display what p[3] stores }
int p[] = {1, 2, 3, 5, 7, 11} initializes an array named p with a list of numbers between braces { }. Keep in mind that p[0] stores 1, p[1] stores 2, p[2] stores 3, p[3] stores 5, and so on. So, print("p[0] = %d\n", p[0]) displays the contents of p[0], which is 1. Likewise, print("p[3] = %d\n", p[3]) displays the contents of p[3], which is 5.
Here is an example that shows how the value of an array element can be reassigned. Take a look at the second to last statement in the main function. It’s p[3] = 101. After that, print("p[3] = %d\n", p[3]) will allow you to verify that the new value p[3] stores is 101.