K&R C Programs Exercise 5-3

Exercise 5-3. Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s.

The Chapter 2 version used array indexing with integer subscripts. The pointer version eliminates the index variables entirely: advance s to its null terminator, then copy t character-by-character (including the null terminator). The compact idiom while ((*s++ = *t++)) does the copy and test in one expression — the assignment’s value is the character written, which is zero (false) when the null terminator is copied.

Solution

/* K&R Exercise 5-3 — strcat with pointers
 * Compile: gcc -ansi -Wall ex5-3.c -o ex5-3 */
#include <stdio.h>

void my_strcat(char *s, const char *t)
{
    while (*s)          /* advance s to the null terminator */
        s++;
    while ((*s++ = *t++))  /* copy t including '\0' */
        ;
}

int main(void)
{
    char buf[50] = "Hello, ";
    my_strcat(buf, "world!");
    printf("%s\n", buf);        /* Hello, world! */

    char s[50] = "foo";
    my_strcat(s, "");           /* concatenate empty string */
    printf("%s\n", s);          /* foo */

    char t[50] = "";
    my_strcat(t, "bar");        /* concatenate onto empty string */
    printf("%s\n", t);          /* bar */
    return 0;
}

Array vs Pointer Version

/* Chapter 2 (array indexing) */
void strcat_array(char s[], char t[])
{
    int i = 0, j = 0;
    while (s[i] != '\0')
        i++;
    while ((s[i++] = t[j++]) != '\0')
        ;
}

/* Exercise 5-3 (pointer arithmetic) */
void strcat_ptr(char *s, const char *t)
{
    while (*s) s++;
    while ((*s++ = *t++))
        ;
}

Both are semantically identical. The pointer version is more idiomatic C and often what you’ll see in real code.

Breaking Down while ((*s++ = *t++))

  1. *t++ — dereference t, then advance t
  2. *s++ = ... — write the character to *s, then advance s
  3. The assignment expression evaluates to the character written
  4. When '\0' is written, the expression is zero (false) and the loop exits

What This Exercise Teaches

  • Pointer advance idiomwhile (*s) s++; walks a pointer to the end of a string without an index
  • Assign-and-test — using the assignment value as the loop condition copies and tests in one step
  • Array indexing and pointer arithmetic are equivalent — same memory access, different notation; the compiler often generates identical code

Set Up Your C Environment

← Exercise 5-2  | 
Chapter 5 Solutions  | 
Exercise 5-4 →

Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>