← 🔤 Strings & Characters
Subtopic 2 of 3

4.2Library functions and pointer loops

The idea

String functions are loops over pointers that stop at the terminator. The classic copy loop is while (*t) *s++ = *t++;.

Think of it like this: A photocopier that stops when it sees the blank page: if you stop it one page early, the blank page is not copied.

Why it exists

Questions give you a short pointer loop and ask what ends up in the buffer, often with overlapping source and destination.

How it works

  1. Both pointers advance together.
  2. The test decides when to stop: while (*t) stops before the terminator, while ((*s++ = *t++)) copies it.
  3. Characters beyond what was copied keep their old value.
  4. Pointer difference b − a after moving b to the terminator equals the length.

Worked example: stringcopy(a, a + 2) on "@#Hello World!"

The loop copies 12 characters from a+2 to a, giving "Hello World!" in positions 0–11. The terminator is not copied, so positions 12 and 13 still hold d !: the output is Hello World!d!.

Now play with it

  • →Run the stops before the terminator tab and watch the array in the stack box.
  • →Compare it with the copy including the terminator program.

The assignment *d++ = *s++ is the loop condition: it copies, and the loop stops after the '\0' has been copied.

step 1 of 9
1#include <stdio.h>
2int main() {
3 char src[] = "abc", dst[8];
4 char *s = src, *d = dst;
5 while ((*d++ = *s++));
6 printf("%s\n", dst);
7 return 0;
8}

The gold line is the statement about to run.

Call stack (top first)
main()
no variables yet
Output

Check yourself

char a[] = "abcd"; char *p = a; while (*p) p++; What is p − a afterwards?

Remember: The loop test decides whether '\0' is copied; leftover characters stay as they were.
Exam notes (the dense version)

strlen counts up to the terminator, strcpy copies including it, strcmp returns 0 for equal strings (negative or positive otherwise, not exactly −1 or 1), strcat appends. The classic copy loop is while (*t) *s++ = *t++;. If the loop stops before copying the terminator, the destination keeps its old tail, as in the 2025 question that printed "Hello World!d!".

Previous year questions: Strings & Characters (3)

PYQs are grouped by topic, so this is the full set for Strings & Characters; try the ones that match this subtopic. Open all 3 on the topic page.