Arrays: collections of elements of the same type
An array is a sequence of elements of the same type stored one next to another in memory. It lets you handle many data items under a single name, such as the grades of a class or the temperatures of a month. Arrays are the basis of strings and matrices and, as you will see in week 5, are closely tied to pointers.
Declaring and initializing
It is declared with the type, the name and the size in brackets: int grades[5]. Indexes start at 0, so the valid elements are grades[0] to grades[4]. You can initialize it with braces; if you give fewer values than the size, the rest is filled with zeros, and if you omit the size the compiler deduces it. Uninitialized, a local array holds garbage, just like a loose variable.
#include <stdio.h>
int main(void) {
int grades[5] = {7, 9, 6, 10, 8};
int zeros[4] = {0}; /* all four elements are 0 */
int primes[] = {2, 3, 5, 7, 11, 13}; /* size 6 deduced */
size_t n = sizeof(primes) / sizeof(primes[0]);
printf("primes has %zu elements\n", n);
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += grades[i];
}
printf("average = %.1f\n", sum / 5.0);
printf("zeros[3] = %d\n", zeros[3]);
return 0;
}The expression sizeof(array) / sizeof(array[0]) computes the number of elements, but it only works where the array is visible as such. As soon as you pass it to a function it becomes a pointer and sizeof no longer helps; that is why functions that receive arrays need an extra parameter with the length.
The danger of going out of bounds
C does not check indexes. Writing grades[5] or grades[-1] in a five-element array compiles fine and accesses memory that is not yours: it can corrupt other variables, crash the program or, worse, seem to work. It is undefined behavior and the cause of countless security failures. The responsibility for respecting the bounds is yours: always validate indexes that come from the user.
#include <stdio.h>
#define SIZE 5
static int get_at(const int *data, size_t len, size_t index, int *out) {
if (index >= len) {
return 0; /* refuse an invalid index */
}
*out = data[index];
return 1;
}
int main(void) {
int data[SIZE] = {10, 20, 30, 40, 50};
int value;
if (get_at(data, SIZE, 2, &value)) {
printf("data[2] = %d\n", value);
}
if (!get_at(data, SIZE, 9, &value)) {
printf("index 9 is out of range\n");
}
return 0;
}Arrays and functions, two-dimensional arrays
When passing an array to a function, it receives the address of the first element, not a copy. That is why a function can modify the elements of the original array, the opposite of what happens with a single int. If the function must only read, mark the parameter const. A two-dimensional array is declared with two sizes, like int board[3][4], and is walked with two nested loops; in memory it is stored row after row.
#include <stdio.h>
static void double_all(int values[], size_t len) {
for (size_t i = 0; i < len; i++) {
values[i] *= 2; /* modifies the caller's array */
}
}
static int sum(const int values[], size_t len) {
int total = 0;
for (size_t i = 0; i < len; i++) {
total += values[i];
}
return total;
}
int main(void) {
int numbers[4] = {1, 2, 3, 4};
double_all(numbers, 4);
printf("sum = %d\n", sum(numbers, 4)); /* 20 */
int board[3][4];
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
board[r][c] = r * 4 + c;
}
}
printf("board[2][3] = %d\n", board[2][3]); /* 11 */
return 0;
}Common mistake: leaving the array and losing the size
C does not check bounds: writing to numbers[10] when the array has 10 elements (indices 0 to 9) gives no compile error, and it may corrupt other variables or end the program without warning. Another common stumble: sizeof(arr) / sizeof(arr[0]) computes the number of elements only inside the function where the array was declared. If you pass the array to another function, it receives a pointer and sizeof returns the size of the pointer, not of the array. That is why functions that receive an array always take a second parameter with the length. Ask for it and use it to limit the loop.
#include <stdio.h>
#include <stddef.h>
int sum(const int *values, size_t count) { /* the length travels with the array */
int total = 0;
for (size_t i = 0; i < count; i++) {
total += values[i];
}
return total;
}
int main(void) {
int numbers[] = {4, 8, 15, 16, 23, 42};
size_t count = sizeof numbers / sizeof numbers[0]; /* 6, valid only here */
printf("%d\n", sum(numbers, count)); /* 108 */
return 0;
}✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters