Strings & string.h Library
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.
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.
#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
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.
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.
Write a program that reads two words from the user and reports whether they are the same word, using strcmp correctly.
#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;
}