liveBook · Manning

String

As explained in Modern C, Third Edition

A C string is an array of char whose elements end with a terminating zero character.

A C string is a 0-terminated array of char. The terminating zero is an additional element: "hello" occupies six char elements, although only five characters are visible. section 6.1.5

char jay0[] = "jay";
char jay1[] = { "jay" };
char jay2[] = { 'j', 'a', 'y', 0, };
char jay3[4] = { 'j', 'a', 'y', };

These declarations initialize equivalent four-element arrays containing j, a, y, and the terminating zero. section 6.1.5

Capacity determines whether an array is a string

char jay4[3] = { 'j', 'a', 'y', }; char jay5[3] = "jay"; Both arrays contain the visible characters but have no remaining element for the terminating zero, so neither is a C string. Arrays also cannot be assigned after initialization. section 6.1.5

The type char encodes characters from C’s basic character set. Standard-library facilities in <string.h> distinguish byte-oriented mem functions, which receive an explicit length, from str functions, which require 0-terminated strings. section 6.1.5

Listing 6.2 Using some of the string functions
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[argc+1]) {
  size_t const len = strlen(argv[0]); // Computes the length
  // Initialized VLA, C23
  // terminates array with 0 character
  char name[len+1] = { };
  // Copies the program name
  memcpy(name, argv[0], len);
  if (!strcmp(name, argv[0])) {
    printf("program name "%s" successfully copied\n",
           name);
  } else {
    printf("copying %s leads to different string %s\n",
           argv[0], name);
  }
}

This program computes a string length, allocates space for its terminator, copies the characters with memcpy, and compares the result with strcmp. section 6.1.5

How Modern C, Third Edition covers it

How deep it goes
Explains termination, initialization, character encoding, and mem-versus-str functions, but defers the complete function catalog.
Examples
Uses equivalent jay declarations, unterminated fixed-size arrays, and a program-name copy using strlen, memcpy, and strcmp.
What it assumes
Assumes familiarity with arrays and introduces char as a narrow integer type used for basic characters.
What you can do after
Apply C strings via <string.h> while allocating and preserving space for the terminating zero.
How it connects
Connects strings with arrays, char, character encoding, and the C standard library.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.