K&R C strings
last modified December 5, 2026 K&R C 1978
C has no string type. A string is an array of characters that
ends with the null character '\0', and a program works with it
through a char pointer to its first character. Everything a
program does with strings, from measuring to copying and comparing, is a
loop over characters until the '\0'. This article writes these
loops, first with indexes and then with pointers, and then turns to the
library.
String constants
A string constant is a sequence of characters in double quotes.
The compiler stores it as an array of characters and adds the
'\0' at the end. In an expression, a string constant is a
pointer to its first character.
#include <stdio.h>
int main()
{
char *s;
int i;
s = "K&R";
printf("%s has size %d\n", s, (int) sizeof "K&R");
for (i = 0; i <= 3; i++)
printf("%d ", s[i]);
printf("\n");
printf("%c\n", "xyz"[1]);
return 0;
}
"K&R" has three characters but takes four bytes. The loop
prints their codes, including the final 0. The assignment
s = "K&R" copies no characters; it only stores the address
of the constant in s. Because a string constant is an array,
it can even be indexed: "xyz"[1] is 'y'.
$ gcc -std=c89 -pedantic -Wall -Wextra -o literal literal.c $ ./literal K&R has size 4 75 38 82 0 y
Character arrays and pointers
A string can be kept in a character array of its own or reached through a pointer. The two look alike in use but are different things.
#include <stdio.h>
int main()
{
static char word[] = "cat"; /* an array of 4 chars */
char *p; /* a pointer */
p = "dog"; /* points to a constant */
printf("%s %s\n", word, p);
word[0] = 'b'; /* the array is ours to change */
p = word; /* the pointer can be moved */
printf("%s %s\n", word, p);
printf("sizeof word = %d, sizeof p = %d\n",
(int) sizeof word, (int) sizeof p);
return 0;
}
word is an array just big enough for "cat" and
its '\0'; the initializer copies the characters into it, and
the program may change them. It is static because an automatic
array cannot be initialized, as the arrays
article shows. p is a pointer: assigning a string constant to
it only points it there, and it can later point somewhere else, here to
word. sizeof gives the size of the array and the
size of the pointer.
$ gcc -std=c89 -pedantic -Wall -Wextra -o char_array char_array.c $ ./char_array cat dog bat bat sizeof word = 4, sizeof p = 8
String length
The length of a string is the number of characters before the
'\0'. Finding it takes a loop, either with an index or with a
pointer.
#include <stdio.h>
/* length of s, with an index */
int len_index(s)
char s[];
{
int i;
i = 0;
while (s[i] != '\0')
++i;
return i;
}
/* length of s, with a pointer */
int len_ptr(s)
char *s;
{
char *p;
p = s;
while (*p != '\0')
p++;
return p - s;
}
int main()
{
static char title[] = "The C Programming Language";
printf("%d %d\n", len_index(title), len_ptr(title));
printf("%d %d\n", len_index(""), len_ptr("Hello there!"));
printf("%d\n", len_ptr(title + 4));
return 0;
}
len_index counts with an index. len_ptr moves a
pointer to the '\0' and subtracts the start, using the pointer
subtraction from the pointers and
arrays article. The empty string "" has length 0.
title + 4 points into the middle of the array, and from there
the string is C Programming Language.
$ gcc -std=c89 -pedantic -Wall -Wextra -o str_len str_len.c $ ./str_len 26 26 0 12 22
Copying a string
The assignment operator does not copy arrays. To copy a string, a program
copies its characters one by one, including the '\0'.
#include <stdio.h>
/* copy t to s, with indexes */
int copy_index(s, t)
char s[], t[];
{
int i;
i = 0;
while ((s[i] = t[i]) != '\0')
i++;
return 0;
}
/* copy t to s, with pointers */
int str_copy(s, t)
char *s, *t;
{
while ((*s++ = *t++) != '\0')
;
return 0;
}
int main()
{
char a[20], b[20];
copy_index(a, "first copy");
str_copy(b, a);
printf("%s, %s\n", a, b);
str_copy(b + 6, "draft"); /* overwrite the end */
printf("%s\n", b);
return 0;
}
Both functions do the assignment inside the loop test and stop after
copying the '\0'. The pointer version is the compact form that
C programmers learn to read at a glance: *s++ = *t++ copies a
character and advances both pointers. The comparison with '\0'
is redundant, because the value of the assignment is 0 exactly then, but it
makes the intent clear. The destination must be large enough; nothing
checks it. Copying to b + 6 replaces the end of the string.
$ gcc -std=c89 -pedantic -Wall -Wextra -o str_copy str_copy.c $ ./str_copy first copy, first copy first draft
Comparing strings
The equality operator on two strings compares their addresses, not their characters. A comparison function walks both strings and returns a value that is negative, zero, or positive, in the same way as subtraction.
#include <stdio.h>
/* <0 if s<t, 0 if s==t, >0 if s>t */
int str_cmp(s, t)
char *s, *t;
{
for ( ; *s == *t; s++, t++)
if (*s == '\0')
return 0;
return *s - *t;
}
int main()
{
printf("%d\n", str_cmp("apple", "apple"));
printf("%d\n", str_cmp("apple", "apricot"));
printf("%d\n", str_cmp("pear", "peach"));
printf("%d\n", str_cmp("pea", "peach"));
printf("%d\n", str_cmp("Zebra", "apple"));
return 0;
}
The loop runs while the characters are equal; if they are equal up to the
end, the strings are the same. Otherwise the result is the difference of the
first characters that differ. "pea" is shorter than
"peach", and its '\0' is less than any character.
The comparison follows the character codes, so Zebra comes
before apple: in ASCII all upper case letters come before
lower case ones.
$ gcc -std=c89 -pedantic -Wall -Wextra -o str_cmp str_cmp.c $ ./str_cmp 0 -2 15 -99 -7
Joining strings
Concatenation appends one string to the end of another. The function first
finds the '\0' of the destination and then copies the second
string over it.
#include <stdio.h>
/* append t to the end of s; s must be big enough */
int str_cat(s, t)
char *s, *t;
{
while (*s != '\0')
s++;
while ((*s++ = *t++) != '\0')
;
return 0;
}
int main()
{
char path[40];
path[0] = '\0'; /* start with an empty string */
str_cat(path, "/usr");
str_cat(path, "/dmr");
str_cat(path, "/notes");
printf("%s\n", path);
return 0;
}
path starts as an empty string, a '\0' in its
first element. Each call appends a part. The destination must have room
for the result; str_cat cannot know the size of the array it
receives.
$ gcc -std=c89 -pedantic -Wall -Wextra -o str_cat str_cat.c $ ./str_cat /usr/dmr/notes
Library string functions
The standard library has functions for the same jobs:
strlen, strcpy, strcmp, and
strcat. They work like our versions; our versions have
different names so that they do not clash with them. GCC declares the
library functions in <string.h>.
#include <stdio.h>
#include <string.h>
int main()
{
char name[40];
strcpy(name, "Dennis");
strcat(name, " ");
strcat(name, "Ritchie");
printf("%s has %d characters\n", name, (int) strlen(name));
if (strcmp(name, "Dennis Ritchie") == 0)
printf("equal\n");
if (strcmp("Kernighan", "Ritchie") < 0)
printf("Kernighan comes first\n");
return 0;
}
strcmp returns 0 for equal strings, so the test is
== 0, and a negative value when the first string sorts first.
strlen returns an unsigned size in GCC's library, and the cast
makes it an int for %d. V7 UNIX has the same
functions in its C library but no <string.h>; a V7
program declares the ones that do not return int, for example
char *strcpy();.
$ gcc -std=c89 -pedantic -Wall -Wextra -o library library.c $ ./library Dennis Ritchie has 14 characters equal Kernighan comes first
Character classes
The header <ctype.h> provides tests for classes of
characters, which do not depend on the character set:
isalpha, isupper, islower,
isdigit, and isspace return a non-zero value when
the character belongs to the class. toupper and
tolower convert letters.
#include <stdio.h>
#include <ctype.h>
/* capitalize the first letter of every word */
int main()
{
int c, prev;
prev = ' ';
while ((c = getchar()) != EOF) {
if (isalpha(c) && !isalpha(prev))
putchar(toupper(c));
else
putchar(c);
prev = c;
}
return 0;
}
The program writes the first letter of every word in upper case. A letter
starts a word when the previous character is not a letter. The tests treat
c as a truth value, so the program does not care what non-zero
value they return. GCC's toupper returns any character that is
not a lower case letter unchanged.
$ gcc -std=c89 -pedantic -Wall -Wextra -o title title.c $ echo 'a tour of Old UNIX in 3 days' | ./title A Tour Of Old UNIX In 3 Days
In V7, toupper(c) is a macro that computes
c - 'a' + 'A' without checking. For a lower case letter it
works; an upper case O becomes / and the
U becomes 5. A portable program of the time
called toupper only after islower had returned
true.
$ cc title.c $ echo 'a tour of Old UNIX in 3 days' | a.out A Tour Of /ld 5NIX In 3 Days
Changing a string constant
The type of a string constant is an array of char, and
nothing in the language stops a program from storing into it through a
pointer. The result, however, is undefined.
#include <stdio.h>
char *greeting()
{
return "hello";
}
int main()
{
char *s;
s = greeting();
printf("%s\n", s);
s[0] = 'j'; /* changes the string constant */
printf("%s\n", greeting());
return 0;
}
greeting returns a pointer to its string constant, and
main changes the first character through it. GCC compiles the
program without a warning, but it places string constants in read-only
memory, and the store crashes the program. GCC's
-Wwrite-strings option makes the compiler treat constants as
read-only and warn about such code.
$ gcc -std=c89 -pedantic -Wall -Wextra -o literal_mod literal_mod.c $ ./literal_mod hello Segmentation fault (core dumped) $ echo $? 139
On the PDP-11 string constants are ordinary data, and the store succeeds.
The change is permanent: the next call of greeting returns the
same, now changed, constant.
$ cc literal_mod.c $ a.out hello jello $ echo $? 0
Source
Dennis Ritchie: C Reference Manual (1975)
Linux manual: string operations
In this article we have worked with strings in K&R C: string constants
and the '\0' that ends them, character arrays and pointers,
our own length, copy, compare, and concatenation functions, the library
functions, character classes from <ctype.h>, and
writable string constants. The next article,
K&R C function pointers, points
to code instead of data. Modern C strings are covered in
C strings.
Author
List all K&R C tutorials.