{ }codelper

Reference › C

C Arrays: Declare, Initialize, and Loop

An array holds several values of the same type side by side. int a[5]; is five int elements, and their indexes run from 0 to 4. You set the size when you create the array, and you can't grow or shrink it later.

type name[size];
type name[size] = {value0, value1, ...};

Create an array, then store and read elements

Write the starting values inside { }. If you write fewer values than the size, the remaining elements become 0. That is why int a[100] = {0}; is the usual idiom for filling everything with 0. You refer to one element as a[index], and you can read and change it like an ordinary variable.

#include <stdio.h> int main(void) {    int a[5] = {10, 20, 30};    a[4] = 50;    a[0] += 1;    for (int i = 0; i < 5; i++) {        printf("a[%d] = %d\n", i, a[i]);    }    return 0;}
Output
a[0] = 11
a[1] = 20
a[2] = 30
a[3] = 0
a[4] = 50

Edit and run it →

Get the number of elements and loop over them all

If you leave the size empty and write int s[] = {...};, you get as many elements as the values you wrote. An array has no built-in way to tell you its length, so you get the number of elements by dividing the total number of bytes by the bytes in one element: sizeof s / sizeof s[0].

#include <stdio.h> int main(void) {    int s[] = {72, 95, 88, 61};    int n = sizeof s / sizeof s[0];    int sum = 0, max = s[0];    for (int i = 0; i < n; i++) {        sum += s[i];        if (s[i] > max) max = s[i];    }    printf("%d %d %d\n", n, sum, max);    return 0;}
Output
4 316 95

Edit and run it →

This only works in the place where the array is declared. You can't use it on an array passed to a function (see the mistakes below).

Fill an array from input

When the count comes from the input, make the array big enough for the largest count that can appear, and keep the number of elements you actually use in a separate variable n. To read into one element, write &a[i].

#include <stdio.h> int main(void) {    int a[100], n, sum = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%d", &a[i]);        sum += a[i];    }    for (int i = 0; i < n; i++) {        if (a[i] * n > sum) printf("%d\n", a[i]);    }    return 0;}
Input
4
7 2 9 4
Output
7
9

Edit and run it →

This prints only the values greater than the average (22 / 4 = 5.5). You only know the average after reading every value, so this is a problem where you have to keep the values in an array. If you want exactly the size that is decided while the program runs, use malloc.

2D arrays

int g[2][3] is a table with 2 rows of 3 elements each. You write g[row][column] and go through it with a nested for.

#include <stdio.h> int main(void) {    int g[2][3] = {{1, 2, 3}, {4, 5, 6}};    for (int r = 0; r < 2; r++) {        int sum = 0;        for (int c = 0; c < 3; c++) {            sum += g[r][c];        }        printf("row %d: %d\n", r, sum);    }    return 0;}
Output
row 0: 6
row 1: 15

Edit and run it →

Common mistakes

Using an element that doesn't exist

int a[5] = {1, 2, 3, 4, 5};
printf("%d\n", a[5]);   /* indexes are 0 to 4 */
a[5] = 99;

→ C does not check whether an index is in range. This is undefined behavior, so you may get a strange value, another variable may change, or the program may crash

With n elements, the last index is n - 1. Write the loop as for (int i = 0; i < n; i++), and before you use an index that came from input, check that 0 <= i && i < n.

Reading an array you never initialized

int count[10];           /* no values stored yet */
count[3]++;
printf("%d\n", count[3]);

→ An array created inside a function starts with unspecified contents. There is no guarantee that this prints 1

Start an array you count with filled with 0, like int count[10] = {0};.

Assigning a whole array or comparing arrays with ==

int a[3] = {1, 2, 3}, b[3];
b = a;              /* does not compile */
if (a == b) { }     /* compares locations (addresses), not contents */

→ The assignment does not compile, and == on two arrays is false even when the contents are the same

Copy and compare one element at a time with a loop. You can also copy with memcpy(b, a, sizeof a); from <string.h>.

Using sizeof inside a function to get the number of elements

int total(int a[]) {
    int n = sizeof a / sizeof a[0];   /* not the number of elements */
    ...
}

→ You get the size of a pointer divided by the size of an int (it differs from computer to computer), not the number of elements in the array

When you pass an array to a function, only the address of its first element goes across. Pass the number of elements separately, like int total(int a[], int n).

Practice problems

See also