Storing Records with Parallel Arrays: Names, Ages, and Marks

In Strings in C: char Arrays, %s, fgets, and strlen you stored a name in a char array, and in the arrays lesson before it you stored five scores in an int array. A real class list needs both, and more: for every student, a name, an age and an average mark. In this lesson you keep a small class list in three arrays that work together, print it as a neat table, type the records in, look one up, find the top mark, and then scramble the records on purpose.

In this lesson you will

  • Describe a student as a record made of fields: name, age and average mark
  • Store the records in parallel arrays, where the same index in every array is one record
  • Print a lined-up table with printf widths such as %-10s, %3d and %6.1f
  • Enter records with fgets and scanf, and deal with the leftover Enter
  • Look up one record by its number, and find the record with the highest mark
  • Break it on purpose: mismatch an index, and reorder one array but not the others

Start a new project for this lesson. Copy 005-StringsCProgram to a new folder named 006-RecordsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Records and fields

The thing we keep data about, here a student, is called an entity. All the data about one student is a record, and each item in the record is a field. Our records have three fields: a name (text), an age (a whole number) and an average mark (a decimal number). Because the fields have different types, they cannot share one array. Instead we use one array per field:

    char names[5][20];   /* 5 names, each up to 19 characters */
    int ages[5];
    float marks[5];

char names[5][20] is an array of 5 strings, and each string is itself a char array of 20. Read it as “5 rows of 20 characters”. names[0] is the first name, and you use it anywhere you used name in the strings lesson. The key idea is that the three arrays are parallel: the same index in each array belongs to the same student. Record 2 is names[2], ages[2] and marks[2], together:

Record (index i)Name: names[i]Age: ages[i]Average mark: marks[i]
0"Ken"1672.5
1"Aaliyah"1788.0
2"Ravi"1664.5
3"Shania"1891.5
4"Marcus"1779.0

Each row is one record. Each column is one field, stored in its own array. Nothing in C ties the three arrays together: the only link between "Ravi", 16 and 64.5 is that they all sit at index 2. Keep that in mind for the break-it sections.

Try it: print the class list

Start with the data typed into the program, using initialiser lists. An array of strings takes a list of string literals:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}
No  Name       Age   Mark
0   Ken         16   72.5
1   Aaliyah     17   88.0
2   Ravi        16   64.5
3   Shania      18   91.5
4   Marcus      17   79.0

The loop is the same for (i = 0; i < 5; i++) pattern from the arrays lesson. On each pass, one printf prints field after field of record i, so one pass is one row of the table.

What just happened: printf widths

A number between the % and the letter is a width: the least number of characters the value takes up. Shorter values are padded with spaces, which is what lines the columns up:

  • %-10s: a string in 10 characters. The - means left-aligned, padded on the right. Ken becomes Ken plus 7 spaces.
  • %3d: an int in 3 characters, right-aligned (no -), so 16 becomes a space and 16.
  • %6.1f: a float in 6 characters with 1 decimal place. You already know .1 from %.2f; the 6 is the width.
  • %-3d: the record number, left-aligned in 3 characters.

The heading line uses the same widths with %s for every column, so the titles sit above their columns. Try changing %-10s to %10s in both lines and run again: the names line up on the right instead. Change it back. A value longer than its width is never cut off; it just pushes the rest of the line along.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i + 1], marks[i]);
    }
    return 0;
}

Break it on purpose: mix up the index

In the loop, change ages[i] to ages[i + 1] and leave the other two as they are. The program is shown above. Build and run. There is no error. On our test computer it printed:

No  Name       Age   Mark
0   Ken         17   72.5
1   Aaliyah     16   88.0
2   Ravi        18   64.5
3   Shania      17   91.5
4   Marcus       0   79.0

Every age is now from the next student: Ken has Aaliyah’s age, Aaliyah has Ravi’s, and so on. Each row looks perfectly sensible, which is what makes this mistake dangerous: the compiler cannot know which age belongs to whom. The last row is worse. For i = 4 it reads ages[5], which is out of bounds, so the 0 is just whatever was in memory there (undefined behaviour, as in the arrays lesson); yours may differ. The rule for parallel arrays: one record, one index, the same in every array. Change it back to ages[i].

Try it: type the records in

Now let the user enter each student. Names can contain a space (Ken Ali), so read them with fgets and remove the Enter, as in the strings lesson. names[i] is a char array, so it needs no &; ages[i] and marks[i] are single numbers, so they do. Here is a first try:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char names[5][20] = {""};
    int ages[5] = {0};
    float marks[5] = {0};
    int i;

    for (i = 0; i < 5; i++)
    {
        printf("Record %d name: ", i);
        fgets(names[i], sizeof(names[i]), stdin);
        names[i][strcspn(names[i], "\n")] = '\0';   /* remove the Enter */
        printf("Age: ");
        scanf("%d", &ages[i]);
        printf("Average mark: ");
        scanf("%f", &marks[i]);
    }

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}

Break it on purpose: forget the leftover Enter

Build and run. Type Ken Ali, 16 and 72.5, pressing Enter after each. Observe: the program never waits for the second name. It jumps straight to Age::

Record 0 name: Ken Ali
Age: 16
Average mark: 72.5
Record 1 name: Age: 

Keep typing the same answers in the same order (Aaliyah Mohammed, 17, 88, and so on) wherever the program stops. On our test computer, the table at the end came out like this:

No  Name       Age   Mark
0   Ken Ali     16   72.5
1                0    0.0
2   Aaliyah Mohammed  17   88.0
3                0    0.0
4   Ravi Singh  16   64.5

Records 1 and 3 are empty and everyone else has shifted down. This is the input buffer again. scanf("%f") read 72.5 and stopped, leaving your Enter waiting. The next fgets read that Enter as a complete, empty line, so record 1 got an empty name. Then scanf("%d") met the letters of Aaliyah, could not read them as a number, and left them (and ages[1], still 0) alone, so the next fgets picked up the name one record late. One leftover Enter threw every record after it out of line.

The fix is to take that one leftover Enter out of the buffer before the next fgets. getchar(), from stdio.h, reads exactly one character. Add it straight after the scanf for the mark:

        scanf("%f", &marks[i]);
        getchar();   /* eat the Enter left after the mark */

Build and run again, and enter all five students:

Record 0 name: Ken Ali
Age: 16
Average mark: 72.5
Record 1 name: Aaliyah Mohammed
Age: 17
Average mark: 88
Record 2 name: Ravi Singh
Age: 16
Average mark: 64.5
Record 3 name: Shania Joseph
Age: 18
Average mark: 91.5
Record 4 name: Marcus Lee
Age: 17
Average mark: 79
No  Name       Age   Mark
0   Ken Ali     16   72.5
1   Aaliyah Mohammed  17   88.0
2   Ravi Singh  16   64.5
3   Shania Joseph  18   91.5
4   Marcus Lee  17   79.0

Every record is right. Notice rows 1 and 3: Aaliyah Mohammed and Shania Joseph are longer than 10 characters, so, as promised, %-10s does not cut them off and the rest of the row is pushed along. Widen the name column to %-18s in both printf lines and the table lines up again. Remember too that each name holds at most 19 characters; fgets stops there, safely.

Try it: look up one record

Because a record is just an index, finding a student by number is one scanf. Go back to the typed-in data and replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};

    int n = 0;

    printf("Which record (0 to 4)? ");
    scanf("%d", &n);

    printf("Name: %s\n", names[n]);
    printf("Age: %d\n", ages[n]);
    printf("Average mark: %.1f\n", marks[n]);
    return 0;
}

Run it and type 3:

Which record (0 to 4)? 3
Name: Shania
Age: 18
Average mark: 91.5

The single number n picks out all three fields of record 3. Now run it again and type 7. There are only 5 records, so names[7], ages[7] and marks[7] are all out of bounds: you may get garbage, an empty name, or a crash. The program cannot refuse a bad number yet, because that needs an if, which you meet properly in a later lesson.

Try it: who has the top mark?

To find the best student, look at every mark and remember the index of the highest so far. This needs one new idea, the if statement, shown here only lightly: if (condition) { ... } runs the statements in the braces only when the condition is true. You will learn it properly later.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    int best = 0;   /* index of the best record so far */

    for (i = 1; i < 5; i++)
    {
        if (marks[i] > marks[best])
        {
            best = i;
        }
    }

    printf("Top mark: %s, age %d, with %.1f\n", names[best], ages[best], marks[best]);
    return 0;
}
Top mark: Shania, age 18, with 91.5

best starts at 0, assuming the first student is the best so far, so the loop starts from index 1. On each pass, marks[i] > marks[best] asks “is this mark higher than the best so far?” If it is, best becomes i. Trace it: 88.0 beats 72.5 (best = 1), 64.5 does not, 91.5 beats 88.0 (best = 3), 79.0 does not. Because best is an index, not a mark, it finds the whole record: the name and age come along for free. Try it: change > to < and the program finds the lowest mark instead. What does it print?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {91.5, 88.0, 79.0, 72.5, 64.5};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}

Break it on purpose: sort one array and not the others

A teacher wants the list from highest mark to lowest. A thought experiment: what if you sort only marks? Go back to the table program and change just the marks list to {91.5, 88.0, 79.0, 72.5, 64.5}, the same five marks in order, leaving names and ages alone. The program is shown above. Build and run:

No  Name       Age   Mark
0   Ken         16   91.5
1   Aaliyah     17   88.0
2   Ravi        16   79.0
3   Shania      18   72.5
4   Marcus      17   64.5

The marks are sorted, but now Ken has Shania’s 91.5 and Shania has Ken’s 72.5. Every mark still exists, but most are attached to the wrong student. With parallel arrays, any reordering must move all the fields of a record together: whenever you move marks[i], you must move names[i] and ages[i] in exactly the same way. Forget one array once, and the records are scrambled for good.

That is the weakness of parallel arrays: the fields of one record are spread across separate arrays, held together only by your care with the index. C has a better tool, the struct, which groups a record’s fields into one variable, so a student’s name, age and mark travel together. Structs are coming in a later lesson.

Common mistakes

  • Using different indexes for the same record, such as names[i] with ages[i + 1].
  • Reordering, adding or deleting in one array but not the others.
  • Forgetting getchar() after scanf, so the next fgets reads an empty line.
  • Putting & in front of names[i] (a string), or leaving it off &ages[i] (a number).
  • Looking up a record number outside 0 to 4.

Key terms

  • Entity: the thing you store data about, here a student.
  • Record: all the data about one entity, such as one student’s name, age and mark.
  • Field: one item in a record, such as the age.
  • Parallel arrays: separate arrays, one per field, where the same index in each array is one record.
  • Array of strings: a two-dimensional char array such as char names[5][20]: 5 strings of up to 19 characters.
  • Field width: the number in a format specifier, such as the 10 in %-10s, giving the least number of characters to print. - means left-aligned.
  • getchar(): reads one character from the input; used here to remove a leftover Enter.
  • if: runs a block of statements only when a condition is true (a full lesson comes later).
  • struct: a C type that groups the fields of a record together (coming in a later lesson).

Quick check

  1. In the class list, which three elements make up record 4?

    Show answer

    names[4], ages[4] and marks[4]: Marcus, 17, 79.0.

  2. What does printf("[%-6s][%4d]", "Ana", 15); print?

    Show answer

    [Ana ][ 15]: Ana left-aligned in 6 characters, 15 right-aligned in 4.

  3. A program reads a mark with scanf("%f", &marks[i]); and then the next name with fgets, but every name after the first is empty. Why, and what is the fix?

    Show answer

    scanf leaves the Enter in the input buffer, and fgets reads it as an empty line. Add getchar(); after the scanf.

  4. Why does the top-mark program remember best as an index rather than the mark itself?

    Show answer

    An index identifies the whole record, so names[best] and ages[best] give the name and age that go with the mark.

  5. You sort names into alphabetical order but leave ages and marks alone. What goes wrong?

    Show answer

    The records are scrambled: names no longer line up with their ages and marks, because each record is held together only by its index.

Part of the Introduction to C series. Next: Storing Data in Files (Plain Text and Binary)

Arrays in C: Storing Many Values Under One Name

Every variable so far has held exactly one value. In Using Library Functions: #include, getch(), and the Input Buffer you used functions that other people wrote; in this lesson you learn to keep a whole list of values under one name. You start with five test scores in five separate variables, feel how quickly that gets painful, then store them in one array, visit every score with a short loop, work out the average, and break it on purpose by reaching past the end.

In this lesson you will

  • See why five separate variables (score1 to score5) do not scale
  • Declare an array, give it a size, and read and write its elements by index, counting from 0
  • Fill an array in one line with an initialiser list { }
  • Meet a first for loop, just enough to visit every index, and use it to print, total and average the scores
  • Read values into the array with scanf
  • Break it on purpose: go past the end, forget the size, copy with =, and use <= in the loop

Start a new project for this lesson. Copy 003-FunctionDemoCProgram to a new folder named 004-ArraysCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Try it: five scores, five variables

Suppose a teacher wants the total of five test scores. With what you know so far, you need one variable per score:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int score1 = 72;
    int score2 = 85;
    int score3 = 64;
    int score4 = 90;
    int score5 = 58;

    int total = score1 + score2 + score3 + score4 + score5;
    printf("Total: %d\n", total);
    return 0;
}
Total: 369

It works, but imagine the class has 30 students. That is 30 declarations, and a sum line with 30 names in it. Miss one and the total is wrong with no error. Every new score means editing the program in several places. What we want is one name for the whole list of scores, and a number that says which score we mean.

Try it: one array, five boxes

Replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5];

    scores[0] = 72;
    scores[1] = 85;
    scores[2] = 64;
    scores[3] = 90;
    scores[4] = 58;

    printf("First score: %d\n", scores[0]);
    printf("Last score: %d\n", scores[4]);

    scores[2] = 70;
    printf("Third score, corrected: %d\n", scores[2]);
    return 0;
}
First score: 72
Last score: 58
Third score, corrected: 70

What just happened

int scores[5]; declares an array of 5 int variables side by side in memory, all called scores. The number in square brackets in the declaration is the size: how many elements (boxes) the array has. After that, a number in square brackets is an index: which box you mean. scores[0] = 72; writes to a box, and scores[0] inside printf reads from it. Each element behaves exactly like an ordinary int variable.

Counting starts at 0. An array of size 5 has indexes 0, 1, 2, 3 and 4. There is no scores[5]. In memory it looks like this:

Elementscores[0]scores[1]scores[2]scores[3]scores[4]
Index01234
Contents7285709058
Which score1st2nd3rd4th5th

Notice that the 1st score is at index 0 and the 5th is at index 4: the index is always one less than the position. Changing scores[2] to 70 changed one box and left the others alone.

Try it: fill it in one line

Writing each element on its own line is still long. You can fill an array as you declare it with an initialiser list: the values in curly braces, separated by commas, in index order:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};

    printf("Second score: %d\n", scores[1]);
    printf("Fourth score: %d\n", scores[3]);
    return 0;
}
Second score: 85
Fourth score: 90

The first value goes into scores[0], the next into scores[1], and so on. If you give fewer values than the size, the rest are set to 0, so int scores[5] = {0}; is a handy way to start with every box at 0, just like the defensive initialisation in the scanf lesson.

Now break the declaration:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[];

    printf("Second score: %d\n", scores[1]);
    printf("Fourth score: %d\n", scores[3]);
    return 0;
}

Break it on purpose: forget the size

Change the declaration to int scores[];, with no size and no initialiser list. Build it. The build stops with:

main.c:6:9: error: array size missing in 'scores'

C must know how many boxes to set aside before the program runs. Either put the size in the brackets, or give an initialiser list so the compiler can count the values: int scores[] = {72, 85, 64, 90, 58}; makes an array of 5. Put the 5 and the list back.

Try it: visit every index with a for loop

Printing each score with its own printf is no better than five variables. The point of an index is that it can be a variable: scores[i] means “the box whose number is in i”. A for loop lets i take the values 0, 1, 2, 3, 4 in turn. Loops get a lesson of their own later. For now, learn this one pattern:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;

    for (i = 0; i < 5; i++)
    {
        printf("scores[%d] = %d\n", i, scores[i]);
    }
    return 0;
}
scores[0] = 72
scores[1] = 85
scores[2] = 64
scores[3] = 90
scores[4] = 58

Read for (i = 0; i < 5; i++) in three parts, separated by semicolons:

  • i = 0: start with i at 0, the first index.
  • i < 5: keep going while i is less than 5, the size. When i reaches 5 the loop stops.
  • i++: after each pass, add 1 to i. It is short for i = i + 1.

The statements in the curly braces run once for each value of i. Change the 5 to 3 and only the first three scores print. Change it back. With 30 students, you would change the array size and the 5 in the loop, and nothing else.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;

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

Break it on purpose: use <= in the loop

Change i < 5 to i <= 5 (“less than or equal to”). Build and run. There is no error and no warning. On our test computer it printed:

scores[0] = 72
scores[1] = 85
scores[2] = 64
scores[3] = 90
scores[4] = 58
scores[5] = 0

Six lines from a five-box array. With <=, the loop also runs when i is 5, and reads scores[5], a box that does not exist. The value you see is whatever happens to be in the memory just after the array, so your number may be different, and it may change from run to run. This is called an off-by-one error. For an array of size 5, the loop test is i < 5, never i <= 5. Change it back.

Try it: total and average

The loop can do more than print. Here it adds each score to a running total, then divides by 5:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;
    int total = 0;
    float average = 0;

    for (i = 0; i < 5; i++)
    {
        total = total + scores[i];
    }

    average = total / 5;

    printf("Total: %d\n", total);
    printf("Average: %.2f\n", average);
    return 0;
}
Total: 369
Average: 73.00

The total is right, but 369 ÷ 5 is 73.8, not 73.00. You have seen this before in the int vs float lesson. total and 5 are both int, so C does whole-number division and truncates the answer to 73 before it is stored in the float. Storing it in a float afterwards cannot bring the .8 back. Make one side of the division a decimal number:

    average = total / 5.0;
Total: 369
Average: 73.80

Trace the loop once by hand: total starts at 0, then becomes 72, 157, 221, 311 and finally 369. If you want to watch it happen, set a breakpoint on the total = total + scores[i]; line and add i and total as watches, as in the debugging lesson.

Try it: read the scores in

Now let the user type the scores. Each element is an ordinary int, so scanf needs its location, with &, just like &x in the scanf lesson:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {0};
    int i;
    int total = 0;

    for (i = 0; i < 5; i++)
    {
        printf("Enter score %d: ", i + 1);
        scanf("%d", &scores[i]);
    }

    for (i = 0; i < 5; i++)
    {
        total = total + scores[i];
    }

    printf("You entered: %d %d %d %d %d\n", scores[0], scores[1], scores[2], scores[3], scores[4]);
    printf("Average: %.2f\n", total / 5.0);
    return 0;
}

Build and run. Type each score and press Enter:

Enter score 1: 72
Enter score 2: 85
Enter score 3: 64
Enter score 4: 90
Enter score 5: 58
You entered: 72 85 64 90 58
Average: 73.80

&scores[i] means “the location of box i”. Each element is one int box, so scanf needs the & in front of it, exactly as for a single variable. The prompt shows i + 1 so that people see 1 to 5, while the program uses indexes 0 to 4.

Try it: one past the end

Replace main with this short program, which asks for the element after the last one:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};

    printf("scores[4] = %d\n", scores[4]);
    printf("scores[5] = %d\n", scores[5]);
    return 0;
}

Break it on purpose: ask for scores[5]

Build and run. On our test computer, GCC gave no error and no warning (even with -Wall), and printed:

scores[4] = 58
scores[5] = 0

C does not check indexes. It works out where box 5 would be and reads that memory, even though it is not part of the array. This is out of bounds access, and the C standard calls the result undefined behaviour: it may print a garbage number, it may print 0 and look fine, it may give a different answer on another computer, or the program may crash. Writing out of bounds, such as scores[5] = 99;, is worse, because it can change some other variable without warning. Keeping every index between 0 and size − 1 is your job, not the compiler’s.

Try it: copy one array into another

Suppose you want a backup of the scores before changing them:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int backup[5];

    backup = scores;
    printf("backup[0] = %d\n", backup[0]);
    return 0;
}

Break it on purpose: copy an array with =

Build it. The build stops with:

main.c:9:12: error: assignment to expression with array type

After it is declared, a whole array cannot be assigned with =. Instead, copy the elements one at a time with the loop.

Replace the backup = scores; line with a loop (and declare int i; with the other variables):

    for (i = 0; i < 5; i++)
    {
        backup[i] = scores[i];
    }
backup[0] = 72

Common mistakes

  • Using index 5 in an array of size 5. The last index is always size − 1.
  • Writing i <= 5 instead of i < 5 in the loop.
  • Forgetting that total / 5 with two ints truncates. Use 5.0.
  • Leaving out the & in scanf("%d", &scores[i]);.
  • Trying to copy or assign a whole array with =.

Key terms

  • Array: a row of variables of the same type under one name, such as int scores[5].
  • Element: one box in an array, such as scores[2].
  • Size: the number of elements, given in the declaration. It cannot change while the program runs.
  • Index: the position of an element, counted from 0. Valid indexes run from 0 to size − 1.
  • Initialiser list: values in curly braces that fill an array as it is declared, such as {72, 85, 64, 90, 58}.
  • for loop: repeats a block of statements; here, once for each index from 0 to size − 1.
  • Off-by-one error: a loop or index that goes one step too far (or stops one step short).
  • Out of bounds: using an index outside the array. C does not check it; the result is undefined behaviour.

Quick check

  1. An array is declared float temps[7];. What are its first and last valid indexes?

    Show answer

    temps[0] and temps[6].

  2. What is in each element after int counts[4] = {3, 9};?

    Show answer

    counts[0] is 3, counts[1] is 9, and counts[2] and counts[3] are 0.

  3. A program prints scores[5] from a size-5 array and gets 0, with no error. Is the program correct?

    Show answer

    No. scores[5] is out of bounds. C does not check it, so the 0 is just whatever was in that memory: undefined behaviour that may print something else, or crash, elsewhere.

  4. A total of 47 is divided by 4 with average = total / 4; and average is a float. What prints with %.2f, and how do you fix it?

    Show answer

    11.00, because int ÷ int truncates. Use total / 4.0 to get 11.75.

  5. Why does scanf("%d", &scores[i]); need the &?

    Show answer

    Each element is an ordinary int variable, and scanf needs its location, just like &x.

Coming up: text is an array too

Every array in this lesson held numbers, but the type in each box can be anything, including char, a single character. Put a row of characters in an array and you have a word. In the next lesson you will see that a string in C is just an array of char, so everything here, from indexes starting at 0 to = refusing to copy, carries straight over.

Part of the Introduction to C series. Next: Strings in C: char Arrays, %s, fgets, and strlen

Strings in C: char Arrays, %s, fgets, and strlen

In the last lesson, Arrays in C: Storing Many Values Under One Name, you stored many numbers under one name in an array. A string is the same idea: an array of char, one character in each box. Every variable so far has held a number, but programs work with text all the time: names, cities, answers. In this lesson you store one character, then a whole word, then read a name from the keyboard and break it on purpose. Along the way you find out what the \0 escape sequence from the printf lesson is for, and meet the input buffer from Using Library Functions: #include, getch(), and the Input Buffer again.

In this lesson you will

  • Store a single character in a char variable and print it with %c
  • Store a word as a string: a row of characters ending in '\0'
  • Print a string with %s and read one with scanf, and find out why it stops at a space
  • Read a whole line safely with fgets, and spot the Enter key it keeps
  • Use strlen and strcpy from string.h, and learn why = cannot copy a string

Start a new project for this lesson. Copy 004-ArraysCProgram to a new folder named 005-StringsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Try it: one character

The data-type table in the int vs float lesson listed char, a type that holds a single character, printed with %c. Try it:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char initial = 'K';

    printf("Your initial is %c\n", initial);
    return 0;
}
Your initial is K

Notice the single quotes. 'K' is a character literal: exactly one character. Double quotes make a string literal, which can hold many. Change 'K' to "K" and the build complains. Change it back.

Try it: a whole word

A char holds one character, so a name needs a whole row of them. Replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[20] = "Ken";

    printf("Hello, %s!\n", name);
    printf("Letters: %c %c %c\n", name[0], name[1], name[2]);
    printf("After the last letter: %d\n", name[3]);

    name[0] = 'B';
    printf("Hello, %s!\n", name);
    return 0;
}
Hello, Ken!
Letters: K e n
After the last letter: 0
Hello, Ben!

What just happened

char name[20] declares an array, just like int scores[5] in the arrays lesson, except that each of its 20 boxes holds a char instead of an int. You reach each one by its index in square brackets, and counting still starts at 0, so name[0] is the first character and name[19] is the last.

Initialising the array with "Ken" fills it like this:

Index01234 to 19
Contents'K''e''n''\0''\0' (unused)

Straight after the last letter sits '\0', the null character. Printed as a number with %d, it shows as 0. This is the end marker that the escape-sequence table promised to explain: in C, a string is a row of characters that ends with '\0'. %s tells printf to start at the first character and keep printing until it reaches the '\0'. Changing name[0] to 'B' changed one box, so the whole word became Ben.

Because the end marker takes up one place, an array of 20 characters can hold a string of at most 19 characters.

Try it: ask for the name

Now let the user type the name. scanf reads a string with %s:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[20] = "";
    char colour[20] = "";

    printf("What is your name?\n");
    scanf("%s", name);
    printf("What is your favourite colour?\n");
    scanf("%s", colour);

    printf("Hello, %s! Your favourite colour is %s.\n", name, colour);
    return 0;
}

Build and run. Type Ken and press Enter, then type blue and press Enter:

What is your name?
Ken
What is your favourite colour?
blue
Hello, Ken! Your favourite colour is blue.

Look closely: there is no & in front of name. In the scanf lesson, scanf needed &x, the location of the variable. The name of an array already stands for the location of its first character, so name on its own is enough. Add an & out of habit and GCC warns:

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat=]

If you tried that, remove the & again and rebuild.

Break it on purpose: type a name with a space

Run the program again. At the first question type Ken Smith and press Enter. Observe: the program does not wait for the colour. It answers straight away:

What is your name?
Ken Smith
What is your favourite colour?
Hello, Ken! Your favourite colour is Smith.

Your surname has become your favourite colour.

%s in scanf reads one word. It stops at the first space, tab or Enter. So name got Ken, and the rest of the line, Smith and the Enter, stayed behind in the input buffer, the same waiting area that caught the held-down key in the previous lesson. The second scanf found Smith already waiting and took it without asking.

Try it: read the whole line with fgets

To read everything the user typed, up to and including the Enter, use fgets (“file get string”). Here the “file” is stdin, the standard input, which is normally the keyboard. The program also uses strlen (“string length”), which counts the characters before the '\0'. It is declared in string.h, so the program includes that header:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char name[20] = "";

    printf("What is your full name?\n");
    fgets(name, sizeof(name), stdin);

    int length = strlen(name);
    printf("Hello, %s!\n", name);
    printf("Your name has %d characters.\n", length);
    return 0;
}

Run it and type Ken Smith. Observe two odd things:

What is your full name?
Ken Smith
Hello, Ken Smith
!
Your name has 10 characters.

The ! has dropped onto the next line, and Ken Smith has 9 characters (the space counts), not 10. Both clues point to the same thing: fgets keeps the Enter key. The string in memory is Ken Smith\n. That hidden \n is the tenth character, and printing it moves the ! to a new line.

fgets takes three things: where to store the text, the size of the array (sizeof(name), here 20), and where to read from (stdin). Because it knows the size, it stores at most 19 characters plus the '\0'.

To remove the Enter, add one line after the fgets. strcspn(name, "\n"), also from string.h, counts the characters before the first \n, which is exactly the index where the \n sits. Putting '\0' there ends the string one place earlier. Rebuild and run with Ken Smith again:

    fgets(name, sizeof(name), stdin);
    name[strcspn(name, "\n")] = '\0';   /* remove the Enter */
What is your full name?
Ken Smith
Hello, Ken Smith!
Your name has 9 characters.

Now try a long name, such as Alexandria Montgomery-Smith. The program prints Hello, Alexandria Montgome! (19 characters). fgets stopped when the array was full and left the rest in the input buffer. Cut off, but safe.

Why the size matters: buffer overflow. scanf("%s", name) does not know how big name is. Type more than 19 characters and it writes past the end of the array, over whatever memory comes next. This is a buffer overflow. The program may crash, quietly change other variables, or work on one computer and fail on another, and attackers use overflows to break into systems. fgets is given the size, so it cannot overflow. (Old books mention a function called gets. It has the same problem and has been removed from C. Never use it.)

Try it: give the string a new value

You can set a number with = at any time, so it seems natural to do the same with a string:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char name[20] = "Ken";
    printf("Before: %s\n", name);

    name = "Kenneth";
    printf("After: %s\n", name);
    return 0;
}

Break it on purpose: copy a string with =

Build it. The build stops with:

main.c:10:10: error: assignment to expression with array type

= worked in the declaration, char name[20] = "Ken";, because that is initialisation: the array is filled as it is created. Afterwards, C does not let you assign a whole array with =.

To copy text into an existing array, use strcpy (“string copy”) from string.h. It copies the characters one by one, including the '\0'. Replace the = line with:

    strcpy(name, "Kenneth");
Before: Ken
After: Kenneth

Read strcpy(name, "Kenneth") as “copy "Kenneth" into name”: the destination comes first, like the left side of =. Like scanf("%s"), strcpy does not check the size, so the destination must be big enough.

Key terms

  • char: a data type that holds a single character, printed with %c.
  • Character literal: one character in single quotes, such as 'K'.
  • Array: a row of variables of the same type under one name, such as char name[20].
  • Index: the position of an item in an array, counted from 0, as in name[0].
  • String: in C, a row of characters in a char array, ending with '\0'.
  • Null character ('\0'): the character with value 0 that marks the end of a string.
  • %s: the format specifier for a string, in both printf and scanf.
  • fgets: reads a whole line of input, up to a size limit, and keeps the Enter (\n).
  • strlen: a string.h function that counts the characters in a string, not including the '\0'.
  • Buffer overflow: writing past the end of an array, into memory that belongs to something else.

Quick check

  1. How big must a char array be to hold the string "Hello"?

    Show answer

    At least 6: five letters plus the '\0' at the end.

  2. A program uses scanf("%s", city); and the user types Port of Spain. What ends up in city, and where is the rest?

    Show answer

    Port. %s stops at the first space, and of Spain plus the Enter wait in the input buffer for the next read.

  3. After fgets(name, sizeof(name), stdin) reads Ana, strlen(name) says 4. Why?

    Show answer

    fgets keeps the Enter, so the string is Ana\n. Remove it with name[strcspn(name, "\n")] = '\0';

  4. city = "Paris"; gives assignment to expression with array type. How do you fix it?

    Show answer

    Use strcpy(city, "Paris"); and add #include <string.h>. Arrays cannot be assigned with = after they are declared.

Part of the Introduction to C series. Next: Storing Records with Parallel Arrays

Updates

2026/10/07
– Moved after the new Arrays lesson and added a link back to it.