C Character Strings: Length, Storage, and Library Operations

C character strings appear in filenames, command arguments, and messages passed between Unix programs. To handle them correctly, you need to track both the text and the storage containing it. The standard header string.h provides operations for measuring, copying, joining, and comparing strings, but these functions depend on you supplying suitable memory.

Bytes, termination, and capacity

A C character string is a contiguous sequence of characters ending with the first null character, written '\0'. This marker is different from the digit '0'. String functions stop at the marker even if the array contains additional characters afterward.


The capacity of a character array is its total available storage in bytes. A char occupies one C byte, so an array of seven characters has a capacity of seven bytes. The string length counts bytes before the first null character and excludes that terminator.


For a string of length LL stored in an array of capacity CC, the storage requirement is


L+1≤C.L + 1 \le C.


The extra byte holds the terminator. An empty string still needs that byte: its first character is '\0', and its length is zero.


Example: The declaration below creates a writable array with seven elements. Initialization stores the three letters, their terminator, and zeros in the remaining elements.


C
char word[7] = "sun";


Seven array cells show sun followed by four null characters, with the first terminator distinguished.


Here, strlen(word) is 3, while sizeof word is 7. This use of sizeof works because word names the actual array; applying sizeof to a pointer does not recover the capacity of the array it addresses. Also, byte length need not equal the number of displayed symbols when text uses a multibyte encoding.

Choosing a string operation

Include the standard header string.h before calling its functions. In these calls, src is the source string and dest is the destination storage.


Function

Purpose

Important condition or result

strlen(s)

Measures bytes before the first null

Returns size_t; does not report capacity

strcpy(dest, src)

Copies the source, including its terminator

Destination needs strlen(src) + 1 bytes

strcat(dest, src)

Appends the source to the destination string

Both inputs must already be terminated

strcmp(a, b)

Compares string contents

Returns a negative value, zero, or a positive value

strncpy(dest, src, n)

Writes a fixed number of destination characters

May omit termination when the source length is at least n


The type size_t is appropriate for lengths and capacities. strcmp compares characters as unsigned-character values at the first difference. Zero means equal contents; otherwise, only the sign of its result is guaranteed, not a particular magnitude such as 1.


Use strcmp(a, b) == 0 to test equal text. The expression a == b compares addresses rather than string contents.

Checking writes before they happen

For concatenation, let LdL_d be the destination's existing length, LsL_s the source length, and CdC_d the destination capacity. Check


Ld+Ls+1≤Cd.L_d + L_s + 1 \le C_d.


strcat replaces the destination's old terminator with the first appended character, then writes a new terminator. It does not enlarge the array or check its capacity.



strncpy requires particular care. For positive n, it writes exactly n destination characters. If the source ends early, it pads the remaining positions with null characters. If the source length is at least n, it copies the first n characters without adding a terminator.



For the copying and concatenation functions above, source and destination storage must not overlap. Destinations must also be writable; attempting to modify a string literal has undefined behavior. Likewise, reading past an array while searching for a missing terminator has undefined behavior. A successful compilation does not establish valid string storage.

What to remember

  • Length excludes the first null character; capacity includes all array storage.
  • Reserve one byte for termination when copying or appending text.
  • Compare contents with strcmp, interpreting its sign rather than assuming an exact nonzero value.
  • Check termination, capacity, writability, and overlap before string operations.

Example: Preparing a Scanner Filename

A scanner utility prepares an output filename using the following writable array. The standard header string.h is included, and each displayed character occupies one byte. The array's capacity is its total storage, including space used by the terminating null character.


C
char name[16] = "scan";


a) Find strlen(name) and sizeof name, and explain why their values differ.


First locate the initial terminator. The four letters occupy indices 0 through 3, so the first null character is at index ________.


strlen counts only those four letters. In contrast, sizeof name measures the actual array declared here, which contains 16 elements of one byte each. Initialization also sets the elements after the first terminator to zero, but those extra elements do not increase the string length.


Therefore, strlen(name) is 4 and sizeof name is 16 bytes.


b) The utility executes strcat(name, ".raw");. Check whether the append fits, then give the resulting text and length.


The source suffix has ________ of text. strcat copies that text and its terminating null character, so it writes ________ starting at the destination's old terminator.


Calculate the total storage needed for the completed string:


Crequired=4+4+1=9 bytes.C_{\text{required}} = 4 + 4 + 1 = 9\ \text{bytes}.


The required storage is ________, which is less than the 16-byte capacity. The old terminator at index 4 is replaced by the period; the new terminator is written at index 8. No source and destination storage overlaps.


The append fits. The resulting string is "scan.raw", and strlen(name) is 8.


c) After the append, evaluate strcmp(name, "scan.raw") and write a condition that tests whether the filename has the expected contents.


Compare the strings character by character. Both contain the same eight text characters followed by a null character. Because there is no differing character, strcmp returns zero.


Use that result directly to test equality:


C
strcmp(name, "scan.raw") == 0


Test contents rather than addresses. Using name == "scan.raw" would compare addresses instead of checking the filename's text.


Therefore, the comparison returns 0, and the condition above is true.

A device stores an identifier in the character array below. With string.h included, what value does strlen(id) return?


C
char id[] = {'4', '0', '\0', '7'};
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A command-line utility compares names using strcmp from string.h. Assume ASCII encoding. Complete each statement with negative, zero, or positive. Give the sign rather than an exact nonzero return value.

  • strcmp("ant", "ape") returns a value.
  • strcmp("log", "log") returns a value.
  • strcmp("report.csv", "report") returns a value.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An export utility copies "item-" into a writable character array, then appends "42" and ".csv". Each displayed character occupies one byte. What minimum array capacity permits the resulting C character string, including its terminator? Answer in bytes as an exact integer.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice