Back to Blog

C in 100 Seconds: Strings | Episode 11

Daryl WongDaryl Wong

Video: C in 100 Seconds: strlen strcpy strcmp — Strings in C | Episode 11 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Strings — Text as Character Arrays in C

C in 100 Seconds, Episode 11


C doesn't have a built-in string type. A string is just an array of characters ending with a null terminator (\0). Everything else is built on top of that.

Declaring a String

char name[] = "Alice";

This creates a 6-element array: {'A', 'l', 'i', 'c', 'e', '\0'}. The null terminator tells functions like printf where the string ends.

String Length

#include <string.h>

printf("Length: %lu\n", strlen(name));  // 5

strlen counts characters up to (but not including) the null terminator. The string.h header gives you all the standard string functions.

Copying Strings

You can't assign strings with = after declaration. Use strcpy:

char copy[20];
strcpy(copy, name);
printf("Copy: %s\n", copy);  // Alice

The destination (copy) must be large enough to hold the source plus the null terminator.

Comparing Strings

The == operator compares addresses, not content. Use strcmp:

printf("Equal? %d\n", strcmp(name, copy) == 0);  // 1 (true)
printf("Compare: %d\n", strcmp("apple", "banana"));  // negative

strcmp returns 0 if the strings are equal, a negative value if the first comes before the second alphabetically, and a positive value otherwise.

Why Does This Matter?

Strings in C require manual management. There's no garbage collector resizing buffers for you. Understanding that strings are just null-terminated character arrays is essential — buffer overflows, one of the most exploited vulnerabilities in software history, come from mishandling them.

Full Code

#include <stdio.h>
#include <string.h>

int main() {
  char name[] = "Alice";
  printf("Name: %s\n", name);
  printf("Length: %lu\n", strlen(name));

  char copy[20];
  strcpy(copy, name);
  printf("Copy: %s\n", copy);

  printf("Equal? %d\n", strcmp(name, copy) == 0);
  printf("Compare: %d\n", strcmp("apple", "banana"));

  return 0;
}

Compile and Run

gcc strings.c -o strings
./strings

Next episode: scanf — reading user input from the terminal.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode11