C Arrays
An array stores several values of the same type in one variable, side by side in memory. Instead of score1, score2, score3, … you create one array scores and reach each value by its position, called the index.
Creating an array
Write the element type, the name, and the number of elements in square brackets. You can fill it with an initialiser list in curly braces:
#include <stdio.h>
int main(void) {
int scores[5] = {72, 88, 95, 60, 81};
printf("First score: %d\n", scores[0]);
printf("Third score: %d\n", scores[2]);
printf("Last score: %d\n", scores[4]);
return 0;
}First score: 72
Third score: 95
Last score: 81
Important: Array indexes start at 0. An array of 5 elements has indexes 0, 1, 2, 3 and 4. There is no
scores[5].
Changing elements
An element is used just like a normal variable — you can read it, assign to it, or use it in calculations:
#include <stdio.h>
int main(void) {
double prices[3] = {2.50, 4.00, 1.25};
prices[1] = 3.75; // change the second element
prices[2] *= 2; // double the third
printf("%.2f %.2f %.2f\n", prices[0], prices[1], prices[2]);
return 0;
}2.50 3.75 2.50
Looping through an array
Arrays and for loops are made for each other. The loop variable walks through every valid index:
#include <stdio.h>
int main(void) {
int temps[7] = {18, 21, 19, 24, 26, 22, 20};
int sum = 0;
int max = temps[0];
for (int i = 0; i < 7; i++) {
printf("Day %d: %d C\n", i + 1, temps[i]);
sum += temps[i];
if (temps[i] > max) {
max = temps[i];
}
}
printf("Average: %.1f C, warmest: %d C\n", sum / 7.0, max);
return 0;
}Day 1: 18 C
Day 2: 21 C
Day 3: 19 C
Day 4: 24 C
Day 5: 26 C
Day 6: 22 C
Day 7: 20 C
Average: 21.4 C, warmest: 26 C
Array size with sizeof
C arrays do not carry their length around. But for an array declared in the current scope, sizeof gives the total size in bytes, and dividing by the size of one element gives the number of elements. If you leave the size out of the brackets, the compiler counts the initialisers for you:
#include <stdio.h>
int main(void) {
int primes[] = {2, 3, 5, 7, 11, 13, 17}; // size inferred: 7
size_t count = sizeof(primes) / sizeof(primes[0]);
printf("sizeof(primes) = %zu bytes\n", sizeof(primes));
printf("number of elements = %zu\n", count);
for (size_t i = 0; i < count; i++) {
printf("%d ", primes[i]);
}
printf("\n");
return 0;
}sizeof(primes) = 28 bytes
number of elements = 7
2 3 5 7 11 13 17
This trick only works on the array itself. Once an array is passed to a function, it becomes a pointer and sizeof returns the pointer size — so functions take the length as a separate parameter (see C Function Parameters).
Partial initialisation
If the initialiser list is shorter than the array, the remaining elements are set to zero. That gives a short way to zero a whole array:
#include <stdio.h>
int main(void) {
int a[6] = {4, 9}; // 4 9 0 0 0 0
int zeros[5] = {0}; // all zero
int picked[5] = {[1] = 7, [4] = 3}; // designated initialisers (C99)
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("\n");
for (int i = 0; i < 5; i++) printf("%d ", zeros[i]);
printf("\n");
for (int i = 0; i < 5; i++) printf("%d ", picked[i]);
printf("\n");
return 0;
}4 9 0 0 0 0
0 0 0 0 0
0 7 0 0 3
A local array without any initialiser contains garbage, just like a plain variable.
Arrays are fixed-size
Once created, an array cannot grow or shrink. Pick a size large enough for your data, or allocate memory dynamically (see C Memory Management). Also, arrays cannot be copied or compared with = and ==; you copy them element by element (or with memcpy).
int a[3] = {1, 2, 3};
int b[3];
b = a; // error: assignment to expression with array typeOut-of-bounds access
C does not check indexes. Writing scores[5] on a 5-element array reads or overwrites whatever memory happens to sit after the array. The program may print garbage, crash, or seem to work and fail later. This is one of the most common sources of serious bugs in C.
Tip: Keep the length in a named constant or compute it with
sizeof, and always loop withi < length, neveri <= length.
Test yourself
What is the index of the last element in int a[10];?
- 10
- 9
- 11
- 1
What are the contents of int v[4] = {5};?
- 5 5 5 5
- 5 0 0 0
- 5 and three garbage values
- It does not compile
Which expression gives the number of elements of an array arr declared in the same scope?
- sizeof(arr)
- length(arr)
- sizeof(arr) / sizeof(arr[0])
- arr.length