$ overview
overview/0x08·Functions & Data

Strings

Why C strings are just arrays of char ending in a zero byte.

C has no dedicated string type. A string is just an array of char, ending with a special sentinel byte, '\0' (the null terminator), that marks where the text stops.

String literals and null termination

literal.c
1char name[] = "Nour";
2// stored in memory as: 'N' 'o' 'u' 'r' '\0'
3// 5 bytes total, even though the word is 4 letters

Every function that works with strings — printf's %s, strlen, strcpy — scans forward until it hits that '\0'. If it's missing, those functions keep reading past the end of your array into whatever memory follows.

Common functions from string.h

string-h.c
1#include <string.h>
2 
3char greeting[50] = "Hello";
4 
5strlen(greeting); // 5 — length, not counting '\0'
6strcat(greeting, ", world!"); // appends onto greeting
7strcpy(greeting, "Hi"); // overwrites greeting's contents
8strcmp("cat", "dog"); // negative: "cat" sorts before "dog"
9strcmp("cat", "cat"); // 0: equal
warning: Destination buffers must have room
strcat and strcpy don't check whether the destination array is big enough — writing past its end corrupts nearby memory. greeting above was declared with 50 bytes specifically to leave room for what gets appended to it. When the size isn't guaranteed, prefer strncat and strncpy, which take a maximum length.

Reading a line of input

scanf("%s", ...) stops at the first whitespace, which makes it unsuitable for names or sentences with spaces. fgets reads a full line, including spaces, and lets you cap how many bytes it writes:

fgets.c
1char line[100];
2printf("Enter your full name: ");
3fgets(line, sizeof(line), stdin);
note: fgets keeps the trailing newline
Unlike scanf, fgets includes the \n the user typed before pressing Enter. It's common to strip it afterward by searching for \n and replacing it with '\0'.

Comparing strings

You cannot compare strings with == — that compares the two array addresses, not their contents. Always use strcmp, which returns 0 when the strings are equal:

compare.c
1if (strcmp(input, "yes") == 0) {
2 printf("Confirmed.\n");
3}