An array keeps many values of the same type under one name, side by side in memory. Instead of five separate variables for five test scores, you make one array and reach each score by its position. Arrays are the starting point for strings, matrices and almost every data structure you will meet later.
In this lesson you will learn
- How to declare an array and read or change its elements
- The different ways to give an array starting values
- How to find the number of elements with
sizeof - How to pass an array to a function
- The mistakes that cause most array bugs
What an Array Is
Picture the seats in one row of a cinema, labelled from 0 upward. Each seat fits exactly one value, and every seat in the row takes the same type, such as int. A seat’s label is called its index. C always starts counting at 0, not 1.
int scores[5]; /* five ints: scores[0] to scores[4] */
This line asks for room for five int values in one block. If an int is 4 bytes, the array takes 20 bytes, and the five values sit next to each other with no gaps.
Reading and Changing Elements
Put the index in square brackets to reach one element. You can read it, print it or give it a new value.
#include <stdio.h>
int main(void) {
int scores[5] = {72, 85, 90, 64, 78};
printf("First score: %d\n", scores[0]);
printf("Last score: %d\n", scores[4]);
scores[3] = 70; /* change one element */
int total = 0;
for (int i = 0; i < 5; i++) {
total += scores[i];
}
printf("Total: %d, average: %.1f\n", total, total / 5.0);
return 0;
}
Output
First score: 72
Last score: 78
Total: 395, average: 79.0
The last element of a five-element array is scores[4]. A for loop from 0 while i < 5 visits every element once, which is the most common pattern in C. Dividing by 5.0 instead of 5 keeps the decimal part of the average.
Giving an Array Starting Values
You can fill an array when you create it. C gives you several shortcuts:
#include <stdio.h>
int main(void) {
int a[5] = {1, 2}; /* rest become 0 */
int b[] = {4, 8, 15, 16, 23}; /* size taken from the list */
int c[6] = {[2] = 9, [5] = 1};/* C99 designated initialisers */
size_t n = sizeof b / sizeof b[0];
printf("b has %zu elements\n", n);
for (int i = 0; i < 5; i++) printf("%d ", a[i]);
printf("\n");
for (int i = 0; i < 6; i++) printf("%d ", c[i]);
printf("\n");
return 0;
}
Output
b has 5 elements
1 2 0 0 0
0 0 9 0 0 1
- Short list: in
a, only two values are given, so the other three become 0. - No size: in
b, the compiler counts the values and makes the array that big. - Chosen positions: in
c,[2] = 9sets one element by index. Everything not named becomes 0. This form needs C99 or later.
The line sizeof b / sizeof b[0] divides the size of the whole array by the size of one element. The answer is the element count. This trick only works where the real array is in scope, as the next section shows.
A local array with no starting values is not set to zero. Its elements hold whatever was in memory before, so always fill it before you read it.
Passing an Array to a Function
When you pass an array to a function, C does not copy it. The function gets the address of the first element. Two things follow from this:
- The function cannot find the length by itself, so you pass the length as a second argument.
- Changes the function makes to the elements are seen by the caller.
#include <stdio.h>
/* The array arrives as a pointer, so the length must be passed too. */
int largest(const int arr[], size_t n) {
int best = arr[0];
for (size_t i = 1; i < n; i++) {
if (arr[i] > best) best = arr[i];
}
return best;
}
void double_all(int arr[], size_t n) {
for (size_t i = 0; i < n; i++) arr[i] *= 2;
}
int main(void) {
int temps[] = {31, 28, 35, 33, 29};
size_t n = sizeof temps / sizeof temps[0];
printf("Hottest: %d\n", largest(temps, n));
double_all(temps, n);
printf("After doubling, temps[0] = %d\n", temps[0]);
return 0;
}
Output
Hottest: 35
After doubling, temps[0] = 62
The const in largest promises that the function only reads the array. The compiler will stop you if you try to change an element there. double_all has no const, and its change to temps is visible back in main. To learn why this happens, see pointer and array relationship in C.
Common Array Mistakes
- Reading past the end. C does not check indexes.
scores[5]in a five-element array reads memory that belongs to something else. The program may print rubbish, crash, or seem fine until later. - Using
<=in the loop.for (i = 0; i <= 5; i++)runs six times. Usei < 5. - Using
sizeofinside a function. There the parameter is a pointer, sosizeof arrgives the pointer’s size (often 8), not the array’s. - Copying with
=.a = b;does not compile for arrays. Copy element by element or usememcpy. - Forgetting to fill a local array. Its starting contents are unknown.
Practice Exercises
Exercise 1. What is printed by int a[4] = {3}; printf("%d", a[3]);?
Show answer
0. Only a[0] gets 3; the rest are set to 0.
Exercise 2. Write a loop that prints an array of 6 ints in reverse order.
Show answer
for (int i = 5; i >= 0; i--) printf("%d ", a[i]);
Exercise 3. A function has the header void show(int arr[]). Why does sizeof arr inside it give 8 on a 64-bit PC?
Show answer
An array parameter is really a pointer, int *arr. A pointer is 8 bytes on a 64-bit system, so you must pass the length separately.
Frequently Asked Questions
Why do C arrays start at index 0?
The index is the distance from the start of the array. The first element is zero steps from the start, so its index is 0.
Can an array hold different types?
No. Every element of an array has the same type. To group different types, use a structure, and make an array of structures if you need many.
Can I change the size of an array later?
Not for an ordinary array; its size is fixed when it is created. If you need a size that grows, allocate the memory with malloc and resize it with realloc, as shown in dynamic memory allocation.
What happens if I access an index that does not exist?
The behaviour is undefined. C does not stop you, so the program may crash or quietly use wrong data. Always keep indexes between 0 and size minus 1.
Summary
- An array stores values of one type next to each other in memory.
- Indexes run from 0 to size minus 1, and C does not check them.
- Missing starting values become 0, but an array with no starting values holds rubbish.
sizeof arr / sizeof arr[0]gives the element count where the array is declared.- Functions receive a pointer to the first element, so pass the length too.
