xSKILLby Infirals
Register

C for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Arrays

Arrays, functions and pointers12 min readLesson 1 of 4

1.1 One name, many slots

An array holds a fixed number of values of the same type in one block of memory. int scores[5]; reserves space for five int values, and each one has a position called an index, numbered from 0.

The number in brackets is the size. C89 requires a constant expression there. C99 added variable-length arrays, and C11 made them optional, so beginner code should use a fixed size.

The first element is scores[0], and the last is scores[4] in a five-element array. There is no scores[5], and C does not check an index at run time. Reading or writing outside the array is undefined behaviour and a common source of crashes.

c
#include <stdio.h>

int main(void)
{
    int scores[5] = {90, 85, 77, 92, 68};

    printf("First: %d\n", scores[0]);
    printf("Last: %d\n", scores[4]);
    printf("Middle: %d\n", scores[2]);
    return 0;
}

Output

First: 90
Last: 68
Middle: 77

1.2 Initialisation

int a[3] = {1, 2, 3}; fills all three elements. int a[3] = {1}; stores 1 in the first and 0 in the rest. A short initialiser list zero-fills the remaining elements, so {1} gives an array with 1 in front and zeros after it.

int a[] = {4, 8, 15, 16}; lets the compiler count the elements and set the size to 4. int a[3] = {1, 2, 3, 4}; is a compile error, because there are more initialisers than elements.

An array declared inside a function without an initialiser holds undetermined values, like any other local variable. Initialise it before reading.

c
#include <stdio.h>

int main(void)
{
    int counted[] = {4, 8, 15, 16};
    int partial[5] = {7};

    printf("counted has %d elements\n",
           (int) (sizeof counted / sizeof counted[0]));
    printf("partial: %d %d %d %d %d\n",
           partial[0], partial[1], partial[2], partial[3], partial[4]);
    return 0;
}

Output

counted has 4 elements
partial: 7 0 0 0 0

1.3 Walking an array with a loop

The length of an array is not stored with it. Inside the function that declares the array, sizeof arr / sizeof arr[0] gives the element count. A function that receives an array cannot use that expression, because the parameter becomes a pointer, and sizeof then reports the size of the pointer.

For a beginner program, the clearest loop is for (int i = 0; i < count; i++). Starting at 0 and comparing with < leaves the last index at count - 1, which is the last valid element.

c
#include <stdio.h>

int main(void)
{
    int values[] = {12, 7, 9, 15, 4};
    int count = (int) (sizeof values / sizeof values[0]);
    int sum = 0;

    for (int i = 0; i < count; i++) {
        sum += values[i];
    }
    printf("Sum: %d, average: %.1f\n", sum, (double) sum / count);
    return 0;
}

Output

Sum: 47, average: 9.4

1.4 Out-of-bounds access

C does not check whether an index is valid. scores[5] on a five-element array reads memory that belongs to something else, and scores[-1] reads before the array. The value you get changes from one run to the next.

A loop written as for (int i = 0; i <= count; i++) reads one element past the end on its last pass.

Undefined behaviour can print a plausible number instead of crashing, so the program looks correct on your machine and fails on another. Use < count in the loop test, and check an index that comes from outside the program with if (index >= 0 && index < count) before using it.

c
#include <stdio.h>

int main(void)
{
    int data[4] = {10, 20, 30, 40};
    int index = 3;

    if (index >= 0 && index < 4) {
        printf("data[%d] = %d\n", index, data[index]);
    } else {
        printf("Index %d is out of range.\n", index);
    }
    return 0;
}

Output

data[3] = 40

1.5 Two-dimensional arrays

A two-dimensional array is an array of arrays. int grid[2][3]; holds 2 rows of 3 columns, and grid[1][2] is row 1, column 2.

The row index comes first. Loop over rows with the outer counter and columns with the inner one, and the printout follows the layout in memory. In memory the rows sit next to each other, so grid[0] is a row of three int values, not a single int.

c
#include <stdio.h>

int main(void)
{
    int grid[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    int sum = 0;

    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            sum += grid[r][c];
        }
    }
    printf("grid[1][2] = %d, total = %d\n", grid[1][2], sum);
    return 0;
}

Output

grid[1][2] = 6, total = 21

1.6 Copying and comparing arrays

An array name in an expression becomes a pointer to its first element, except as the operand of sizeof or &. That rule explains why int b[5] = a; does not copy an array: it converts a to a pointer, and the initialiser is invalid.

Copy element by element in a loop, or use memcpy from <string.h> with a byte count from sizeof.

There is no operator that compares two arrays by content. if (a == b) compares addresses, which is almost never what you meant. Write a loop that compares each pair and stops at the first mismatch.

c
#include <stdio.h>

int main(void)
{
    int source[4] = {2, 4, 6, 8};
    int copy[4] = {0};

    for (int i = 0; i < 4; i++) {
        copy[i] = source[i];
    }
    copy[2] = 99;

    printf("source[2] = %d\n", source[2]);
    printf("copy[2] = %d\n", copy[2]);
    return 0;
}

Output

source[2] = 6
copy[2] = 99

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01Why does an array index start at zero?

    The index counts elements from the start of the block, so the first element sits at offset 0. An array with `n` elements has valid indices from 0 through `n - 1`.

  • 02How do you find the number of elements in an array?

    In the scope where the array is declared, divide the total size by the size of one element: `sizeof arr / sizeof arr[0]`. The result has type `size_t`, so store it in `size_t` or cast it before printing with `%d`.

  • 03What happens when you read `arr[10]` in an array of 10 elements?

    The program reads memory past the end of the array. C does not check the index, so the value is whatever lies there. The program may crash, or it may continue with a meaningless number.

Quiz

Check: C arrays

Four questions on indexing, initialisation, bounds and measuring an array's length.

4 questions

Question 1 of 4

0/4 answered

In int scores[5], the last valid index is:

Answer all you can, then submit.