Codiqo

Learn C · lesson 25 of 60 · about 7 minutes

Declaring and Indexing Arrays

Show the CPU's cores: store several values of one type in an array, and read them by position.

What you'll learn

  • Declare and initialise an array
  • Read and change items by index
  • Work out an array's length with sizeof

The CPU's cores

The machine's CPU has 4 cores, and the report should say how busy each one is. Four separate variables would work until the report runs on a machine with 8. An array, int cores[], keeps all the loads in a row under one name, and a typed core number can pick one out, as long as it's checked first: C won't stop you reading past the end.

A row of boxes

An array is a fixed-size row of values of the same type, stored side by side in memory:

int scores[4] = {70, 85, 90, 62};

Positions (indexes) start at 0, so the last item of a 4-item array is at index 3. The size can't change after the array is created.

Reading and changing items

#include <stdio.h>

int main(void) {
    int scores[4] = {70, 85, 90, 62};
    printf("First: %d\n", scores[0]);
    printf("Last: %d\n", scores[3]);
    scores[1] = 88;
    printf("Second is now %d\n", scores[1]);
    return 0;
}

Output

First: 70
Last: 62
Second is now 88

How many items?

sizeof(scores) is the size of the whole array in bytes, and sizeof(scores[0]) is the size of one item. Dividing them gives the number of items, which saves you hard-coding it.

Counting items

#include <stdio.h>

int main(void) {
    double prices[] = {1.5, 2.25, 4.0};
    int n = sizeof(prices) / sizeof(prices[0]);
    printf("%d prices, last is %.2f\n", n, prices[n - 1]);
    return 0;
}

Output

3 prices, last is 4.00

Tip

C does not check indexes. Reading scores[10] from a 4-item array won't stop the program: it reads whatever memory is there. Always keep indexes between 0 and length - 1.

Tip

An array can't be copied or assigned with = after it's made. To copy one, copy its items one at a time in a loop.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.