Lesson 17 / 36

string.h Functions

Standard helpers for length, copy, compare and concatenation.

strlen & strcpy

strlen counts characters before '\0' (excluding it). strcpy copies a string including its null terminator.

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

char src[] = "hello";
char dest[10];

printf("%zu\n", strlen(src)); // 5
strcpy(dest, src);
printf("%s\n", dest);

Output:

5
hello

strcmp & strcat

strcmp returns 0 when strings are equal (never use == to compare strings!). strcat appends one string to another.

char a[20] = "cat";
char b[]   = "cat";

if (strcmp(a, b) == 0) {
    printf("equal\n");
}

strcat(a, "fish");
printf("%s\n", a);

Output:

equal
catfish

Buffer must be big enough

strcpy/strcat don't check the destination's size — writing past it corrupts memory. Prefer strncpy/strncat with an explicit size limit.

Quick check: Why should you avoid `if (str1 == str2)` to compare two C strings?

  • It compares pointer addresses, not contents
  • It always returns true
  • It only works with numbers
Answer

It compares pointer addresses, not contents — Arrays decay to pointers, so `==` compares addresses; use `strcmp` for content.