Strings & string.h Library

⚙️ C Language 🟢 Lesson 10 of 20 📅 2026 Edition
C has no built-in string type — a string is simply an array of characters ending with a special terminator. This lesson explains that underlying structure and introduces the string.h library that handles common string tasks.
1Strings Are Character Arrays
C Language ▶ Run Code
char name[6] = "Hello";   // stored as: 'H' 'e' 'l' 'l' 'o' '\0'

Every C string ends with a hidden null terminator, written '\0', which marks where the string stops. This is why a string holding 5 visible characters needs an array of at least 6 — one extra slot for the terminator. Functions like printf("%s") read characters until they hit this terminator.

2Reading and Printing Strings
C Language ▶ Run Code
char name[50];
printf("Enter your name: ");
scanf("%49s", name);        // no & needed - array name already IS an address
printf("Hello, %s!\n", name);

Unlike other variable types, you never put & before a character array in scanf() — the array's name already refers to its starting memory address.

3Key string.h Functions
C Language ▶ Run Code
#include <string.h>

char first[20] = "Hello";
char second[20] = "World";

printf("%zu\n", strlen(first));         // 5 - length, not counting the terminator
strcat(first, second);              // joins: first becomes "HelloWorld"
printf("%d\n", strcmp("abc", "abc")); // 0 if equal, non-zero otherwise
strcpy(first, "New Value");            // overwrites first's contents
4Why You Can't Use == to Compare Strings

Writing if (name1 == name2) compares the memory addresses of the two arrays, not their actual text content — this almost never does what a beginner expects. Always use strcmp(name1, name2) == 0 to properly compare whether two strings contain the same characters.

⚠️ Common Mistake: Comparing Strings with == Instead of strcmp()

This produces one of the most confusing bugs for beginners coming from other languages: name1 == name2 compiles fine and sometimes even seems to work by coincidence, but it's actually comparing memory addresses, not text. Always use strcmp() from string.h, and check if the result equals 0 for equality.

💻 Try It Yourself

Write a program that reads two words from the user and reports whether they are the same word, using strcmp correctly.

C Language ▶ Run Code
#include <stdio.h>
#include <string.h>

int main() {
    char word1[30], word2[30];

    printf("Enter first word: ");
    scanf("%29s", word1);
    printf("Enter second word: ");
    scanf("%29s", word2);

    if (strcmp(word1, word2) == 0) {
        printf("The words match!\n");
    } else {
        printf("The words are different.\n");
    }
    return 0;
}
Run This in Our Compiler →