Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 135 ยท Arrays and Strings

Arrays

Learn C arrays from scratch - declaring, initializing and designated initializers, indexing and loops, sizeof tricks, passing arrays to functions, and bounds errors.

Programs rarely work with just one value. A week of temperatures, the scores in a game, the pixels in a row of an image: each is a list of values of the same type. In C you store such a list in an array, a fixed number of elements of one type placed side by side in memory.

Arrays are the simplest data structure C has, and also the foundation for strings, matrices, buffers and almost every other structure you'll build later. They're fast because elements sit next to each other, but they come with one rule you must never forget: C doesn't check whether an index is valid. This lesson covers declaring and initializing arrays, looping over them, measuring them with sizeof, passing them to functions, and staying inside their bounds.

Declaring an array

You declare an array by giving the element type, a name, and the number of elements in square brackets:

C
int scores[5];          // 5 ints
double readings[24];    // 24 doubles
char initials[3];       // 3 chars

The size must be a positive integer. For an ordinary array it's usually a constant expression: a literal, an enum constant, a macro or (in C23) a constexpr variable. A size computed at run time creates a variable-length array, a special case covered in Multidimensional Arrays.

C
#define MAX_PLAYERS 8
enum { DAYS_PER_WEEK = 7 };

int points[MAX_PLAYERS];
double rainfall[DAYS_PER_WEEK];

Naming the size once (instead of writing 8 in several places) means you can change it in one spot, and your loops stay correct. Constants compares the ways to do that.

In memory, the five ints of scores are stored one after another with no gaps. If an int is 4 bytes, the whole array takes 20 bytes:

TEXT
int scores[5];

index:      0       1       2       3       4
        +-------+-------+-------+-------+-------+
        |       |       |       |       |       |
        +-------+-------+-------+-------+-------+
byte:   0       4       8       12      16      20

Initializing arrays

A local array that you don't initialize contains garbage: whatever bytes happened to be in that memory. Reading them is a bug. Give arrays a value when you declare them, using a brace-enclosed list:

C Ways to initialize an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
full         90 85 77 62 98
partial      1 2 0 0 0
zeros        0 0 0 0 0
empty        0 0 0 0 0
counted      4 8 15 16 23 42
sparse       0 0 7 0 0 3 0 1

The rules to remember:

  • Missing elements are zero. If you give fewer values than the size, every remaining element is set to 0. So zeroes the whole array, and C23's {} does the same. (Before C23, empty braces were a GCC extension, so use in portable code.)
  • Too many values is a mistake. The standard forbids it; for int a[2] = {1, 2, 3}; GCC prints "excess elements in array initializer" and drops the extra value.
  • You can omit the size when you provide an initializer: the compiler counts the values.
  • Designated initializers ([index] = value) set specific elements, in any order. They're perfect for lookup tables, and mixing them with plain values continues from the last designated index: {[3] = 1, 2, 3} sets indexes 3, 4 and 5.
  • Global and static arrays start as zeros even without an initializer. Only local (automatic) arrays start with garbage. Scope and Storage Classes explains why.

An initializer list only works in a declaration. Once an array exists, you can't assign a whole new list to it; you change elements one at a time.

Indexing and looping

You read and write elements with the subscript operator, array[index]. Indexes start at 0, so an array of n elements has valid indexes 0 to n - 1:

C
int scores[5] = {90, 85, 77, 62, 98};
scores[0] = 91;          // first element
scores[4] += 2;          // last element: 100
int third = scores[2];   // 77

An index can be any integer expression, which is what makes arrays so useful with loops. The canonical loop runs from 0 while the index is less than the count:

C Reading numbers into an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With the preset input it prints:

TEXT
count: 7
min 3, max 25, average 12.57
above average: 19 25 14

Edit the Input box and run it again with your own numbers. A few habits in this program are worth copying:

  • The loop condition checks count < CAPACITY before reading, so the program can never write past the end of values, however much input arrives.
  • scanf returns how many values it converted. Stopping when it isn't 1 handles both the end of input and text that isn't a number (see Reading Input with scanf and fgets).
  • size_t is the natural type for sizes and indexes: it's unsigned and big enough for any array. Print it with %zu.
  • min and max start at the first element, not at some "large" number that might be wrong.

sizeof and the number of elements

sizeof applied to an array gives its total size in bytes. Divide by the size of one element to get the number of elements:

C
int counted[] = {4, 8, 15, 16, 23, 42};
size_t bytes = sizeof counted;                      // 24 if int is 4 bytes
size_t length = sizeof counted / sizeof counted[0]; // 6, on every platform

Using sizeof counted[0] instead of sizeof(int) keeps the expression correct even if you later change the element type. Many projects wrap it in a macro:

C
#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))

This trick has one big limitation: it only works where the compiler can see the real array. That leads to the most important fact about arrays and functions.

Passing arrays to functions

When you pass an array to a function, C doesn't copy it. The array decays into a pointer to its first element, and the function receives that pointer. These three parameter declarations are exactly the same:

C
void fill(int values[], size_t count);
void fill(int values[10], size_t count);   // the 10 is ignored!
void fill(int *values, size_t count);

Two consequences follow, and this example shows both:

C Arrays decay to pointers in function calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints:

TEXT
in main: sizeof prices = 24, count = 6
inside the function: sizeof values = 8
after double_all: 10 24 14 60 2 18
total = 128

The compiler also warns about show_size, because this mistake is so common:

TEXT
warning: 'sizeof' on array function parameter 'values' will return size of 'int *' [-Wsizeof-array-argument]

So:

  1. The function works on the caller's array. double_all changed prices in main. If a function shouldn't modify the array, mark the parameter const, as total does; the compiler then rejects any accidental write.
  2. The function doesn't know the length. Inside it, sizeof gives the size of a pointer (8 bytes on 64-bit systems). Always pass the element count as a separate parameter, conventionally of type size_t, right after the array.

The Pointers and Arrays lesson explains decay in detail, including why values[i] works on a pointer at all.

What you can't do with arrays

Arrays aren't values the way ints are. Three operations that seem natural don't work:

C
int a[3] = {1, 2, 3};
int b[3];

b = a;          // error: assignment to expression with array type
if (a == b)     // compiles, but compares ADDRESSES (warning: comparison between two arrays)
return a;       // functions can't return arrays

To copy an array, copy the elements with a loop or with memcpy from <string.h>. To compare two arrays, compare element by element (or with memcmp for plain integer data). To return an array, have the caller pass one in, return a struct that contains an array, or allocate memory dynamically.

C Copying, comparing and reversing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints equal after copy: yes, then reversed: 6 2 9 5 1 4 1 3, equal after reverse: no and struct copy: 7 8 9. The reverse function swaps from both ends toward the middle, a pattern you'll reuse for strings. The count < 2 check matters: with count == 0, count - 1 would wrap around to a huge unsigned number.

No bounds checking

Here is the rule this lesson promised: C does not check array indexes. Reading or writing scores[5] in a five-element array, or scores[-1], is undefined behavior. The program might print garbage, crash, corrupt other variables, or appear to work perfectly until the day it doesn't. Out-of-bounds writes are the root of buffer-overflow security holes.

The most common cause is an off-by-one loop:

C
int scores[5] = {90, 85, 77, 62, 98};
int total = 0;
for (int i = 0; i <= 5; i++) {   // BUG: <= runs i = 5, one past the end
    total += scores[i];
}

GCC can sometimes spot this when sizes and loop bounds are constants. For the loop above, -O1 -Wall produces:

TEXT
warning: iteration 5 invokes undefined behavior [-Waggressive-loop-optimizations]

When we ran it, it printed a nonsense total. On another compiler or another day it could print something else, or the optimizer could even remove the loop's exit check entirely. Don't count on warnings: most out-of-bounds bugs involve indexes computed at run time, which the compiler can't check.

Protect every index that comes from outside your code. If a number came from input, a file or a calculation, check index < count (and index >= 0 for signed types) before using it. Write loops as for (size_t i = 0; i < count; i++), with <, never <=. Tools like AddressSanitizer (-fsanitize=address) catch out-of-bounds accesses at run time during testing; Memory Errors shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int a[6] = {[1] = 5, 9}; contain?

    The designated initializer sets index 1 to 5, and the next plain value continues at index 2. Every element not mentioned is 0.
  2. 2. A function is declared void f(int values[10]). Inside f, what is sizeof values on a 64-bit system?

    An array parameter is really a pointer, and the 10 is ignored. sizeof gives the size of int *, which is 8 bytes on 64-bit systems. Pass the length separately.
  3. 3. What happens when a program reads scores[5] from int scores[5]?

    C never checks indexes. Accessing one past the last valid index (4) is undefined behavior; it might print garbage, crash or seem to work.
  4. 4. Given int a[3] = {1, 2, 3}; int b[3];, which line copies a into b correctly?

    Arrays can't be assigned with =, and brace lists only work in declarations. memcpy copies all sizeof a bytes, or you can copy element by element in a loop.
  5. 5. What does this print? int n[] = {2, 4, 6, 8}; printf("%zu", sizeof n / sizeof n[0]);

    sizeof n is the size of the whole array (16 bytes with 4-byte ints) and sizeof n[0] is one element (4 bytes), so the quotient is the element count, 4.

Summary

  • An array holds a fixed number of elements of one type, stored contiguously: int scores[5];.
  • Initialize with braces; missing elements become 0, (or C23 {}) zeroes everything, and designated initializers set chosen indexes.
  • Indexes run from 0 to n - 1; loop with for (size_t i = 0; i < n; i++).
  • sizeof array / sizeof array[0] gives the element count, but only where the real array is visible.
  • Arrays passed to functions decay to pointers: the function can modify the caller's elements, and you must pass the length separately. Use const for read-only parameters.
  • Arrays can't be assigned, compared with == or returned; use loops, memcpy and memcmp.
  • C never checks bounds. Out-of-range access is undefined behavior, so validate every index.

Next: Multidimensional Arrays, where arrays get rows and columns.