ZetCode

K&R C arrays

last modified December 5, 2026 K&R C 1978

An array is a sequence of variables of the same type, stored one after another in memory and selected by an integer index. C arrays are simple: they have a fixed size known to the compiler, the first element has index 0, and nothing checks that an index is inside the array. This article declares and initializes arrays, uses them for counting, passes them to functions, and stores lines of text in character arrays.

Declaring and indexing

The declaration int sq[10]; makes an array of ten int elements. The elements are sq[0] to sq[9]; the index may be any integer expression.

squares.c
#include <stdio.h>

#define N 10

int main()
{
    int sq[N];
    int i;

    for (i = 0; i < N; i++)
        sq[i] = i * i;
    for (i = 0; i < N; i++)
        printf("%d ", sq[i]);
    printf("\n");
    return 0;
}

The first loop stores the square of each index, the second prints the elements. The size is a symbolic constant, so it is written in one place; the loops run from 0 while the index is less than N, which is the usual form of a loop over an array. Like any automatic variable, the array holds garbage until the program stores something in it.

$ gcc -std=c89 -pedantic -Wall -Wextra -o squares squares.c
$ ./squares
0 1 4 9 16 25 36 49 64 81 

Initializing arrays

External and static arrays can be given initial values: a list of constants in braces. When the size is left out, the compiler counts the initializers. When the list is shorter than the array, the remaining elements are zero.

days.c
#include <stdio.h>

int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int counts[5] = { 7, 8 };

int main()
{
    static int primes[] = { 2, 3, 5, 7, 11, 13 };
    int i, total, n;

    total = 0;
    for (i = 0; i < 12; i++)
        total = total + days[i];
    printf("days in a year: %d\n", total);

    n = sizeof primes / sizeof primes[0];
    printf("%d primes, the last is %d\n", n, primes[n - 1]);

    for (i = 0; i < 5; i++)
        printf("%d ", counts[i]);
    printf("\n");
    return 0;
}

days gets its twelve elements from the list, and counts has five elements of which only the first two are given; the rest are 0. The operator sizeof gives the size of the whole array in bytes, so dividing it by the size of one element gives the number of elements. This keeps the count correct when the list is edited. The array primes is local to main, so it is declared static to allow an initializer.

$ gcc -std=c89 -pedantic -Wall -Wextra -o days days.c
$ ./days
days in a year: 365
6 primes, the last is 13
7 8 0 0 0 

Initializing a local array

K&R C does not allow an automatic array to be initialized. The values of an automatic variable must be set each time the function is entered, and the compiler only does this for single variables.

auto_init.c
#include <stdio.h>

int main()
{
    int coins[] = { 1, 2, 5, 10, 20, 50 };
    int i;

    for (i = 0; i < 6; i++)
        printf("%d ", coins[i]);
    printf("\n");
    return 0;
}

GCC accepts the initializer and sets up the array on each call, so the program works with GCC.

$ gcc -std=c89 -pedantic -Wall -Wextra -o auto_init auto_init.c
$ ./auto_init
1 2 5 10 20 50 

The PDP-11 compiler follows the rules of the book and stops with three errors. The fix is the one from the previous section: declare the array static, or fill it with assignments.

$ cc auto_init.c
auto_init.c:5: No auto. aggregate initialization
auto_init.c:5: 0-length row: coins
auto_init.c:5: Too many initializers: coins

Counting with an array

An array of counters, indexed by a value computed from the input, replaces a long chain of separate variables and tests. This program counts each of the ten digits, the white space characters, and all other characters.

digits.c
#include <stdio.h>

/* count each digit, white space, and other characters */
int main()
{
    int c, i, white, other;
    int ndigit[10];

    white = other = 0;
    for (i = 0; i < 10; i++)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
        if (c >= '0' && c <= '9')
            ++ndigit[c - '0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++white;
        else
            ++other;

    for (i = 0; i < 10; i++)
        printf("%d: %d\n", i, ndigit[i]);
    printf("white space: %d, other: %d\n", white, other);
    return 0;
}

c - '0' turns a digit character into its value from 0 to 9, which is the index of its counter, so ++ndigit[c - '0'] counts the digit. This relies on the digits having consecutive codes, which every character set guarantees. The counters are set to zero in a loop, since an automatic array cannot be initialized. The while loop body is a single if statement and needs no braces.

$ gcc -std=c89 -pedantic -Wall -Wextra -o digits digits.c
$ echo 'Call 555 0199 or 555 0123 before 18:00.' | ./digits
0: 4
1: 3
2: 1
3: 1
4: 0
5: 6
6: 0
7: 0
8: 1
9: 2
white space: 8, other: 14

A histogram

A program can print the counts of an array as a picture. This one counts the words of each length and draws a bar of stars for each length. A word is a run of letters.

lengths.c
#include <stdio.h>

#define MAXLEN 8    /* longer words are counted as MAXLEN */

/* print a histogram of the word lengths of the input */
int main()
{
    int c, i, j, len;
    int nlen[MAXLEN + 1];

    for (i = 0; i <= MAXLEN; i++)
        nlen[i] = 0;

    len = 0;
    while ((c = getchar()) != EOF) {
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            ++len;
        else if (len > 0) {
            if (len > MAXLEN)
                len = MAXLEN;
            ++nlen[len];
            len = 0;
        }
    }

    for (i = 1; i <= MAXLEN; i++) {
        printf("%2d %2d ", i, nlen[i]);
        for (j = 0; j < nlen[i]; j++)
            putchar('*');
        putchar('\n');
    }
    return 0;
}

len counts the letters of the current word. When a character that is not a letter ends a word, the counter for its length is incremented and len starts again. Words longer than MAXLEN are counted in the last element, so the index never goes past the end of the array. %2d prints a number in a field two characters wide.

$ gcc -std=c89 -pedantic -Wall -Wextra -o lengths lengths.c
$ ./lengths < poem.txt
 1  1 *
 2  9 *********
 3 18 ******************
 4  9 *********
 5 15 ***************
 6  1 *
 7  3 ***
 8  0 

Arrays as arguments

An array is passed to a function by giving its name. The parameter is declared as an array without a size, because the function can work with an array of any length. The length is passed as a separate argument.

arg_array.c
#include <stdio.h>

/* return the sum of the first n elements of v */
int sum(v, n)
int v[];
int n;
{
    int i, s;

    s = 0;
    for (i = 0; i < n; i++)
        s = s + v[i];
    return s;
}

/* reverse the first n elements of v in place */
int reverse(v, n)
int v[];
int n;
{
    int i, j, t;

    for (i = 0, j = n - 1; i < j; i++, j--) {
        t = v[i];
        v[i] = v[j];
        v[j] = t;
    }
    return 0;
}

int main()
{
    static int marks[] = { 3, 1, 4, 1, 5, 9, 2, 6 };
    int i;

    printf("sum %d\n", sum(marks, 8));
    reverse(marks, 8);
    for (i = 0; i < 8; i++)
        printf("%d ", marks[i]);
    printf("\n");
    return 0;
}

reverse swaps the first and last elements and moves inwards; the comma operator lets the loop update both indexes. Unlike other arguments, the array is not copied: the function receives the address of its first element and works on the caller's array, so the change made by reverse is seen in main. The pointers article explains how this works.

$ gcc -std=c89 -pedantic -Wall -Wextra -o arg_array arg_array.c
$ ./arg_array
sum 31
6 2 9 5 1 4 1 3 

Character arrays

Text is stored in arrays of char. By convention, a string ends with the null character '\0', whose value is 0; the character array must have room for it. A function that reads a line into an array needs to know the size of the array, so that it does not write past its end.

line_len.c
#include <stdio.h>

#define MAXLINE 100

/* read a line into s, return its length */
int get_line(s, lim)
char s[];
int lim;
{
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        i++;
    }
    s[i] = '\0';
    return i;
}

int main()
{
    char line[MAXLINE];
    int len;

    while ((len = get_line(line, MAXLINE)) > 0)
        printf("%2d %s", len, line);
    return 0;
}

get_line reads characters until a newline, the end of input, or a full array. It keeps the newline, ends the string with '\0', and returns the length, so a length of 0 means the end of the input; an empty line has length 1. The name has an underscore because the UNIX library already has a getline. printf with %s prints the characters of an array up to the '\0'.

$ gcc -std=c89 -pedantic -Wall -Wextra -o line_len line_len.c
$ ./line_len < poem.txt
35 The tide comes in without a sound,
37 it fills the harbour stone by stone,
32 and every boat that lay aground
30 is lifted up and rides alone.
 1 
31 The gulls go quiet one by one,
34 the lamps are lit along the quay;
37 the tide goes out when night is done
37 and takes the boats back out to sea.

The longest line

To remember a line, the program must copy it into a second array before the next line overwrites it. This program prints the longest line of its input.

longest.c
#include <stdio.h>

#define MAXLINE 100

int get_line(s, lim)
char s[];
int lim;
{
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        i++;
    }
    s[i] = '\0';
    return i;
}

/* copy the string from into to */
int copy_line(to, from)
char to[], from[];
{
    int i;

    for (i = 0; (to[i] = from[i]) != '\0'; i++)
        ;
    return 0;
}

/* print the longest input line */
int main()
{
    char line[MAXLINE], longest[MAXLINE];
    int len, max;

    max = 0;
    while ((len = get_line(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy_line(longest, line);
        }
    if (max > 0)
        printf("%d: %s", max, longest);
    return 0;
}

copy_line copies characters until it has copied the '\0'. The assignment inside the test does the work, and the loop body is an empty statement, a lone semicolon on its own line. Two lines have 37 characters; the test len > max keeps the first. The strings article returns to copying and comparing strings.

$ gcc -std=c89 -pedantic -Wall -Wextra -o longest longest.c
$ ./longest < poem.txt
37: it fills the harbour stone by stone,

Two-dimensional arrays

A two-dimensional array is an array whose elements are arrays. It is declared with two sizes, int t[3][4], and its elements are selected with two indexes, t[i][j]. The elements are stored row by row.

sales.c
#include <stdio.h>

#define SHOPS  3
#define MONTHS 4

int sales[SHOPS][MONTHS] = {
    { 12, 15,  9, 20 },
    {  8, 11, 14, 10 },
    { 17,  6, 13, 19 }
};

/* the total of one row */
int row_total(t, r)
int t[][MONTHS];
int r;
{
    int j, s;

    s = 0;
    for (j = 0; j < MONTHS; j++)
        s = s + t[r][j];
    return s;
}

int main()
{
    int i, j, col;

    for (i = 0; i < SHOPS; i++) {
        for (j = 0; j < MONTHS; j++)
            printf("%4d", sales[i][j]);
        printf(" | %4d\n", row_total(sales, i));
    }
    printf("----------------------\n");
    for (j = 0; j < MONTHS; j++) {
        col = 0;
        for (i = 0; i < SHOPS; i++)
            col = col + sales[i][j];
        printf("%4d", col);
    }
    printf("\n");
    return 0;
}

The table holds the sales of three shops in four months; each row of the initializer is in its own braces. A function that takes a two-dimensional array must know the number of columns to find a row, so the parameter is declared int t[][MONTHS]; only the number of rows may be left out. The row totals come from row_total, the column totals from a loop in main.

$ gcc -std=c89 -pedantic -Wall -Wextra -o sales sales.c
$ ./sales
  12  15   9  20 |   56
   8  11  14  10 |   43
  17   6  13  19 |   55
----------------------
  37  32  36  49

Array bounds

C does not check array indexes. An index past the end of an array refers to whatever lies in memory after it, and storing there silently changes another variable.

bounds.c
#include <stdio.h>

#define N 4

int first[N];
int second[N];

int main()
{
    int i;

    for (i = 0; i < N; i++)
        second[i] = 100 + i;

    for (i = 0; i <= N; i++)    /* one element too many */
        first[i] = i;

    for (i = 0; i < N; i++)
        printf("%d ", second[i]);
    printf("\n");
    return 0;
}

The second loop runs while i <= N and stores into first[4], which does not exist. Both GCC and the PDP-11 compiler place second directly after first, so the extra store overwrites second[0]. On another compiler it could change a different variable or crash the program. The usual cause is the loop condition: an array of N elements has indexes 0 to N - 1.

$ gcc -std=c89 -pedantic -Wall -Wextra -o bounds bounds.c
$ ./bounds
4 101 102 103 

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Options to Request or Suppress Warnings

In this article we have worked with arrays in K&R C: declaration and indexing, initialization of external and static arrays, counting and histograms, arrays passed to functions, character arrays that hold lines, two-dimensional arrays, and the missing bounds checks. The next article, K&R C pointers, introduces the addresses that arrays are passed by. Modern C arrays are covered in C arrays.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.