Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Arrays and strings

By the end of this chapter, you'll be able to

  • Declare, initialise and go through an array with a for loop
  • Pass an array and its size to a function
  • Explain the role of the end-of-string character '\0'
  • Use strlen and strcmp from <string.h>
  • Recognise an access outside the bounds of an array

Arrays

#include <stdio.h>

int main(void) {
    double temp[7] = {28.5, 30.0, 31.5, 29.0, 27.5, 26.0, 30.5};
    double sum = 0;
    for (int i = 0; i < 7; i++) {
        sum += temp[i];
    }
    printf("Monday: %.1f, Sunday: %.1f\n", temp[0], temp[6]);
    printf("Average: %.2f\n", sum / 7);
    return 0;
}
Monday: 28.5, Sunday: 30.5
Average: 29.00
  • double temp[7] reserves 7 boxes of type double, contiguous in memory. The size is fixed once and for all.
  • The boxes are numbered from 0 to 6: temp[0] is the first, temp[6] the last. This number is called the index.
  • {…} gives the initial values. If you give fewer than the size, the remaining boxes are 0: int t[100] = {0}; fills everything with zeros.

To know the number of boxes without repeating it, divide the total size by the size of one box: sizeof temp / sizeof temp[0] is 7. The sizeof operator gives a size in bytes.

Passing an array to a function

A function that receives an array doesn't know its size. So we always pass it as an extra parameter:

#include <stdio.h>

int maximum(const int t[], int n) {
    int max = t[0];
    for (int i = 1; i < n; i++) {
        if (t[i] > max) {
            max = t[i];
        }
    }
    return max;
}

int main(void) {
    int scores[] = {12, 45, 7, 45, 31};
    int n = sizeof scores / sizeof scores[0];
    printf("Best score: %d\n", maximum(scores, n));
    return 0;
}
Best score: 45

const promises that the function won't change the array: the compiler will refuse any write to t. Unlike simple variables, an array isn't copied when you pass it to a function: the function works directly on the original boxes. You'll understand why in the chapter on pointers.

Strings

A string is an array of char ending with a special character, '\0' (the null character, code 0). It's this marker that tells where the text stops.

The displayed text has changed.

Step 5 of 5
Text description of the animation
  1. Two strings: a city and a country code.
  2. "GHA" has 3 letters, but takes 4 boxes: the last one holds the end marker '\0'.
  3. %s displays the characters one by one, until it meets '\0'.
  4. A string is an array: you can change one box.
  5. The displayed text has changed.

The <string.h> library provides the useful functions. strlen returns the length (not counting '\0'), and strcmp compares two strings: it returns 0 if they're identical.

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

int main(void) {
    char word[] = "kalanblon";
    char attempt[] = "kalanblon";
    printf("Length: %zu\n", strlen(word));
    if (strcmp(word, attempt) == 0) {
        printf("Password correct\n");
    }
    return 0;
}
Length: 9
Password correct

strlen returns a size_t, a positive integer meant for sizes, displayed with %zu. Careful: strlen counts bytes. An accented character like é takes two in UTF-8, so strlen("Lomé") is 5.

To compare two strings, never use ==: it would compare the locations of the two arrays in memory, not their contents.

Your turn

Worked exercise

Worked exercise: counting a letter

Write a function int count(const char text[], char letter) that returns the number of times letter appears in text. Then display the number of ms in "programming" (answer: 2).

Hint 1
You don't need the size: go through the text as long as text[i] != '\0'.
Hint 2
Characters are compared with ==, between single quotes: text[i] == letter.
Show the solution and common mistakes
#include <stdio.h>

int count(const char text[], char letter) {
    int total = 0;
    for (int i = 0; text[i] != '\0'; i++) {
        if (text[i] == letter) {
            total++;
        }
    }
    return total;
}

int main(void) {
    printf("%d\n", count("programming", 'm'));
    printf("%d\n", count("banana", 'n'));
    return 0;
}
2
2

Common mistakes:

  • Writing "m" instead of 'm': double quotes create a string (an array), not a character. -Wall points out the invalid comparison.
  • Using i < strlen(text) without <string.h>, or with an int: -Wextra points out the comparison between a signed integer and a size_t. Testing for '\0' avoids the problem.

Summary

  1. 1An array stores n values of the same type, numbered from 0 to n - 1.
  2. 2C doesn't check indexes: going outside an array is a serious and silent error.
  3. 3A function that receives an array also needs its size.
  4. 4A string is an array of char ending with '\0': always leave a box for it.
  5. 5strlen gives the length, strcmp compares: never == between two strings.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.