C / CHAPTER 04

Arrays, lengths, and terminated text

Intermediate

Track element bounds and distinguish a character array from a string literal.

By the end of this chapter

  • Compute a local array length
  • Reserve room for the string terminator
  • Change only writable array elements

The idea

This chapter assumes loops and declarations. An array contains a fixed number of consecutive elements. Valid indexes begin at zero and stop before that count. For a local array object, dividing sizeof the array by sizeof one element computes its element count without assuming how many bytes the element type occupies. This calculation does not recover a length from a pointer parameter.

A C string is a character sequence ending in a zero character. An initialized array such as char label[] = "fern" includes storage for that terminator and can be edited within its bounds. A string literal is not writable storage merely because a pointer can refer to it. When copying or assembling text, the capacity must include the terminator as well as the visible characters.

C example
#include <stdio.h>
#include <string.h>
int main(void){char label[]="reed"; label[0]='R'; printf("%s %zu %zu\n",label,sizeof label,strlen(label));}
Result
Reed 5 4

The array occupies five char elements including the terminator. strlen counts the four characters before that terminator.

Try it yourself

Create a six-element char array holding the five-letter string orbit and change only its first letter.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

How many char elements are in char word[] = "oak";?