An array is a variable that stores multiple values.

Every value in the array, in C, must have the same type. This means you will have arrays of int values, arrays of double values, and more.

You can define an array of int values like this:

int prices[5];

You must always specify the size of the array. C does not provide dynamic arrays out of the box (you have to use a data structure like a linked list for that).

You can use a constant to define the size:

const int SIZE = 5;
int prices[SIZE];

You can initialize an array at definition time, like this:

int prices[5] = { 1, 2, 3, 4, 5 };

But you can also assign a value after the definition, in this way:

int prices[5];

prices[0] = 1;
prices[1] = 2;
prices[2] = 3;
prices[3] = 4;
prices[4] = 5;

Or, more practical, using a loop:

int prices[5];

for (int i = 0; i < 5; i++) {
  prices[i] = i + 1;
}

And you can reference an item in the array by using square brackets after the array variable name, adding an integer to determine the index value. Like this:

prices[0]; /* array item value: 1 */
prices[1]; /* array item value: 2 */

Array indexes start from 0, so an array with 5 items, like the prices array above, will have items ranging from prices[0] to prices[4].

The interesting thing about C arrays is that all elements of an array are stored sequentially, one right after another. Not something that normally happens with higher-level programming languages.

Another interesting thing is this: the variable name of the array, prices in the above example, is a pointer to the first element of the array, and as such can be used like a normal pointer.

More on pointers soon.


Download my free C Beginner's Handbook!


Check out my in-depth, practical Web Development Courses!

(all 50% off with the coupon code POSITIVEVIBRATIONS)

⤴️⤴️⤴️