Skip to content

Beginner · Functions and arrays · topic 14 of 60 · 25 min

Arrays

Explanation

An array stores a fixed number of elements of one type in consecutive memory, indexed from 0. int marks[5] = {0}; zeroes all five. sizeof(arr) / sizeof(arr[0]) gives the count only where the array is declared. C never checks bounds: reading or writing outside the array is undefined behaviour. When passed to a function, an array becomes a pointer, so pass its length too.

Declaring and initialising

c
int marks[5];                       /* 5 ints, uninitialised if local (garbage) */
int prices[] = {499, 120, 2999};    /* size 3 worked out from the initialiser */
int zeros[100] = {0};               /* all 100 elements set to 0 */
double temps[7] = {31.5, 33.0};     /* first two set, the remaining five are 0.0 */
int days[12] = { [1] = 28 };        /* C99 designated initialiser: element 1 is 28, others 0 */

marks[0] = 78;
marks[4] = 91;                      /* valid indexes: 0 to 4 */

Arrays in memory

output
int a[4] = {10, 20, 30, 40};

address   element   value
0x1000    a[0]      10
0x1004    a[1]      20      (each int is 4 bytes here)
0x1008    a[2]      30
0x100C    a[3]      40
Elements sit next to each other, which makes indexing very fast: the address of a[i] is start + i × sizeof(int).

Counting elements

c
int prices[] = {499, 120, 2999, 75};
size_t n = sizeof prices / sizeof prices[0];   /* 16 / 4 = 4 */
for (size_t i = 0; i < n; i++) printf("%d\n", prices[i]);
Careful: C does not check array bounds. prices[4] on a 4-element array, or a loop with i <= n, reads or writes memory that belongs to something else. The program may print garbage, corrupt other variables, crash, or seem to work and fail later. This is the cause of buffer-overflow security holes. Always loop with i < n, and test with -fsanitize=address, which reports out-of-bounds access immediately.

Passing arrays to functions

c
int sum(const int a[], size_t n) {        /* a is really a pointer: const int *a */
    int total = 0;
    for (size_t i = 0; i < n; i++) total += a[i];
    return total;
}

void apply_discount(int a[], size_t n, int percent) {   /* no const: it changes the caller's array */
    for (size_t i = 0; i < n; i++) a[i] -= a[i] * percent / 100;
}

int main(void) {
    int prices[] = {500, 200, 1000};
    size_t n = sizeof prices / sizeof prices[0];
    apply_discount(prices, n, 10);           /* prices is now {450, 180, 900} */
    printf("%d\n", sum(prices, n));           /* 1530 */
    return 0;
}

An array is not copied when passed; the function receives the address of the first element (the array "decays" to a pointer, module 5). So the function can change the caller's elements, and inside the function sizeof a gives the size of a pointer (8), not of the array. That is why you always pass the length separately. Mark parameters const when the function only reads.

Arrays cannot be assigned

int b[3] = a; and b = a; do not compile. Copy element by element in a loop, or with memcpy(b, a, sizeof a) from <string.h>. Comparing with a == b compares addresses, not contents.

Think of it like this: An array is like a row of numbered lockers at a railway station, each the same size, side by side. Locker numbers start at 0. Nothing stops you from putting your bag in locker number 50 of a 40-locker row, except that it belongs to somebody else, and that is exactly the kind of mistake C will not catch for you.
Tip: Keep the array and its length together: pass both to every function, or wrap them in a struct (module 7).

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrays · 1/6

Arrays

In this lesson you will store many values in a C array.

Prefer a video by a teacher? Find free videos on “c arrays tutorial passing arrays to functions sizeof bounds” on YouTube ↗

In real life: Monthly sales in a shop

A small shop's program stores 12 monthly sales figures in an array, finds the best month and the total, and passes the array with its length to helper functions.

c
#include <stdio.h>

int best_month(const int sales[], int n) {
    int best = 0;
    for (int i = 1; i < n; i++) if (sales[i] > sales[best]) best = i;
    return best;
}

int main(void) {
    int sales[12] = {42, 38, 51, 47, 60, 55, 49, 52, 58, 71, 83, 64};   /* in thousands of rupees */
    int m = best_month(sales, 12);
    printf("Best month: %d (Rs %d thousand)\n", m + 1, sales[m]);   /* Best month: 11 (Rs 83 thousand) */
    return 0;
}

Practice (0/3 done)

Task 1 · Question

What does this print? int a[5] = {1, 2}; printf("%d %d\n", a[1], a[4]);

Task 2 · Question

Inside void f(int a[]) on a 64-bit Linux system, sizeof a is…

Task 3 · Practice

Write a program with an array of 10 temperatures. Write functions to compute the average (const array parameter), find the index of the maximum, and count readings above a threshold. Then write a function that converts every reading from Celsius to Fahrenheit in place (non-const parameter). Print the array before and after.

Quick quiz

Question 1

1.What is the index of the last element of int a[10]?

Question 2

2.Which copies array a (3 ints) into array b?

Question 3

3.Does C check array bounds at run time?

Question 4

4.int a[] = {4, 5, 6, 7}; What is sizeof a / sizeof a[0]?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the index of the last element of int a[10]?

Answer: 9

Indexes run from 0 to 9.

Which copies array a (3 ints) into array b?

Answer: memcpy(b, a, sizeof a);

Arrays cannot be assigned; copy the bytes or loop.

Does C check array bounds at run time?

Answer: No: out-of-bounds access is undefined behaviour

Use sanitizers when testing.

int a[] = {4, 5, 6, 7}; What is sizeof a / sizeof a[0]?

Answer: 4

Total bytes divided by bytes per element.

Where does an array NOT decay to a pointer?Related

Answer: In sizeof a

sizeof (and &a) see the whole array.

From Pointers and arrays

How do you get the length of an array arr?Related

Answer: arr.length

For arrays, length is a field (no brackets). Strings use length().

From Arrays

What is the index of the last item in an array of length 8?Related

Answer: 7

Indexes go from 0 to Length - 1.

From Arrays: one name, many values

What is the index of the LAST element of an array of size 10?Related

Answer: 9

Indexes run from 0 to size - 1.

From Arrays, std::array and a first look at std::vector

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Functions and arrays” before its exam: 2D arrays and classic array algorithms.
  2. Module 3 exam: Functions and arrays · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Strings in C. 60 topics left in the course before the final exam.

← Previous: Recursion