Module 5 · Arrays and Strings — topic 3 of 3
Strings
A C string is an array of char ending with the null character '\0'. Learn how strings are stored, read and printed, and how to use strlen, strcpy, strcat, strcmp and their safer bounded versions.
Learning objectives
- Declare and initialise strings as char arrays
- Use <string.h> functions correctly
- Read strings safely with fgets and avoid buffer overflows
Definition
A string in C is a contiguous sequence of characters terminated by and including the first null character ('\0'). String literals are arrays ofcharwith static storage duration; functions in<string.h>operate on strings through pointers to their first character.
Introduction
C has no built-in string type. Text is stored in a char array, and the end of the text is marked by a zero byte, '\0'. Every string function relies on finding that terminator.
This design is simple and fast, but it is also behind many of the most famous security vulnerabilities in history: copy a 30-character name into a 20-character array and the extra bytes overwrite whatever lies next in memory.
Why it matters
Text processing — names, commands, files, network messages — is everywhere. Knowing how C strings work is required for file handling, command-line arguments and almost every project in this course.
String questions (strlen vs sizeof, comparing with ==, reversing, palindromes, counting vowels) are among the most common in C interviews.
Detailed explanation
char name[] = "Ravi"; creates a 5-byte array: 'R' 'a' 'v' 'i' '\0'. char name[20] = "Ravi"; reserves 20 bytes; the unused ones are zero.
strlen(s) counts characters before the terminator (4 for "Ravi"). sizeof name gives the array size in bytes (5 or 20), and only works on arrays.
Strings cannot be assigned or compared with operators. Use strcpy(dest, src) to copy, strcat(dest, src) to append, and strcmp(a, b) to compare: it returns 0 if equal, a negative value if a sorts first, positive otherwise.
Bounded versions limit how much is written: snprintf(dest, size, "%s", src) always null-terminates and is the safest general tool. strncpy does not add a terminator when the source is too long, so it must be used carefully.
For input, scanf("%19s", buf) reads one word. To read a whole line including spaces, use fgets(buf, sizeof buf, stdin), which keeps the newline; remove it with buf[strcspn(buf, "\n")] = '\0';.
Syntax
- Always leave room for the terminator: n characters need n + 1 bytes.
"A"is a string (2 bytes);'A'is a character (an int).- Include
<string.h>for the string functions.
Code examples
Length vs size
strlen = 9 sizeof = 20 last char = d
Copy, append, compare
Ada Lovelace (12 chars) 0 1
More examples
Reading a line and analysing it
Never odd or even
Enter a sentence: "Never odd or even" 4 words, 6 vowels palindrome: yes
Step-by-step explanation
fgetsreads the whole line, including spaces, but never more than 99 characters plus the terminator.line[strcspn(line, "\n")] = '\0';replaces the newline thatfgetskeeps.- The loop stops at
'\0'— the standard way to walk a C string. - A word starts each time a non-space character follows a space (the
in_wordflag). is_palindromecompares from both ends, skipping spaces and ignoring case withtolower.- Casting to
unsigned charbefore calling<ctype.h>functions avoids undefined behaviour for negativecharvalues.
Expected output
Running “Reading a line and analysing it” with the sample input shown prints exactly:
Practical applications
- Command interpreters split input lines into words.
- Web servers parse HTTP headers, which are null-terminated strings in C implementations.
- Buffer overflows from
strcpyandgetscaused real attacks such as the 1988 Morris worm.
Best practices
- Size buffers generously and always pass their size to input functions.
- Prefer
snprintfandfgetsoverstrcpy,strcatandgets. - Declare pointers to literals as
const char *.
Common mistakes
Comparing strings with ==
Avoid
Prefer
== compares addresses, not characters. Two equal strings at different addresses compare unequal.
No room for the terminator
Avoid
Prefer
"ABCD" needs 5 bytes. With 4, C drops the terminator (legal in C, an error in C++) and string functions read past the end.
Modifying a string literal
Avoid
Prefer
A pointer to a literal may point into read-only memory; writing to it is undefined behaviour and often crashes. An array is a modifiable copy.
Important notes
getswas removed in C11 because it cannot be used safely. Some compilers still provide it with a warning — never use it.strlenwalks the whole string each call; calling it in a loop condition (i < strlen(s)) makes the loop O(n²). Store the length in a variable.
Key takeaways
- C strings are char arrays ending with '\0'.
- Use
strlenfor length,strcmpfor comparison,snprintf/fgetsfor safe writing and reading. - Always reserve one extra byte for the terminator.
Try it yourself
- 1Write your own
my_strlenandmy_strcpyusing loops and compare their results with the library versions. - 2Read a line and print it with each word's first letter capitalised.
- 3Count the frequency of each letter in a sentence (ignore case).
Finished reading? Mark it complete to update your dashboard.
Suggested practice
12 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerHow many bytes does the string literal "code" occupy?
- BeginnerWhy is `if (name == "admin")` wrong for checking a string?