C Strings

C strings are arrays of characters that end with a special null character, written '\0'. C has no built-in string type, so understanding this null terminator is the key to working with text in C.

Creating Strings

A string literal automatically gets a '\0' at the end, so "Cat" needs 4 bytes.

#include <stdio.h>

int main(void) {
    char pet[] = "Cat";       // {'C','a','t','\0'}
    printf("%s has %zu bytes\n", pet, sizeof pet);
    printf("First letter: %c\n", pet[0]);
    return 0;
}
Cat has 4 bytes
First letter: C

Common string.h Functions

  • strlen(s): number of characters before the null terminator
  • strcpy(dest, src) / strncpy: copy a string
  • strcat(dest, src) / strncat: append one string to another
  • strcmp(a, b): compare; returns 0 when equal
  • strchr(s, c) and strstr(s, sub): search for a character or substring

Using C String Functions

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

int main(void) {
    char full[40] = "Naeem";
    strcat(full, " Amin");
    printf("%s (%zu chars)\n", full, strlen(full));

    if (strcmp(full, "Naeem Amin") == 0) {
        printf("Names match\n");
    }
    return 0;
}
Naeem Amin (10 chars)
Names match

Safe String Building with snprintf

strcpy and strcat do not check the destination size. snprintf never writes past the size you give, so it is a safer way to build strings.

#include <stdio.h>

int main(void) {
    char msg[32];
    int items = 3;
    snprintf(msg, sizeof msg, "You have %d new items", items);
    printf("%s\n", msg);
    return 0;
}
You have 3 new items

Comparing Strings Correctly

Never compare strings with ==. That compares addresses, not contents. Always use strcmp, which returns 0 for equal strings, a negative number if the first comes earlier alphabetically, and a positive number otherwise.

Frequently asked questions

Why can't I compare strings with == in C?

A string name evaluates to the address of its first character, so == checks whether two strings are at the same memory location. Use strcmp to compare their contents.

What is the null terminator in C?

It is the character '\0' (value 0) that marks the end of a string. Functions like printf and strlen read characters until they reach it.

What is the difference between strlen and sizeof for strings?

strlen counts characters before the null terminator. sizeof gives the total bytes of the array, including the terminator and any unused space.