Strings
C has no string type - just arrays of characters ending in a zero. Here is how to work with them safely.
- Explain how C stores strings with a null terminator
- Use
strlen,strcpy/snprintfandstrcmpcorrectly - Read a line of text safely with
fgets
A string in C is an array of char whose last character is the null terminator '\0' - a byte with value zero. Every string function relies on it: that zero is the only way to know where the string ends.
1#include <stdio.h>
2
3int main(void) {
4 char word[] = "Hi!"; // 4 bytes: 'H' 'i' '!' '\0'
5 printf("%s has %zu bytes\n", word, sizeof word);
6 for (int i = 0; word[i] != '\0'; i++) {
7 printf("word[%d] = '%c'\n", i, word[i]);
8 }
9 return 0;
10}Hi! has 4 bytes word[0] = 'H' word[1] = 'i' word[2] = '!'
The string "Hi!" has 3 visible characters but takes 4 bytes. Forgetting to leave room for the terminator is one of the most common C bugs. When you size a buffer, always think "length + 1".
String literals and char pointers
char name[] = "Ada"; creates your own modifiable array, copied from the literal. const char *name = "Ada"; instead points at the literal itself, which lives in read-only memory - trying to modify it is undefined behavior. That is why the pointer is declared const: use it for strings you only read.
The <string.h> toolkit
| Function | Does |
| --- | --- |
| strlen(s) | number of characters before the '\0' (not counting it) |
| strcmp(a, b) | compares: 0 if equal, negative if a sorts first, positive otherwise |
| strcpy(dest, src) | copies src into dest - no size check |
| strcat(dest, src) | appends src to dest - no size check |
| snprintf(dest, size, fmt, ...) | printf into a buffer, never writing more than size bytes |
1#include <stdio.h>
2#include <string.h>
3
4int main(void) {
5 const char *password = "hunter2";
6 char attempt[] = "hunter2";
7
8 if (password == attempt) {
9 printf("== says equal\n");
10 }
11 if (strcmp(password, attempt) == 0) {
12 printf("strcmp says equal\n");
13 }
14 printf("length: %zu\n", strlen(attempt));
15 return 0;
16}strcmp says equal length: 7
Reading a line with fgets
scanf("%s", buf) stops at the first space and has no idea how big buf is. To read a whole line safely, use fgets(buf, sizeof buf, stdin): it reads at most sizeof buf - 1 characters and adds the terminator. It keeps the newline character, which you usually want to remove:
1#include <stdio.h>
2#include <string.h>
3
4int main(void) {
5 char name[64];
6 if (fgets(name, sizeof name, stdin) == NULL) {
7 return 1;
8 }
9 name[strcspn(name, "\n")] = '\0'; // chop the newline
10 printf("Hello, %s!\n", name);
11 return 0;
12}strcspn(name, "\n") returns the index of the first newline (or the string length if there is none), so writing '\0' there cleanly trims it.
Key takeaways
A C string is a
chararray ending in'\0'; it needs length + 1 bytes.Compare with
strcmp(a, b) == 0, never==. Measure withstrlen(which excludes the terminator).Prefer bounded functions:
snprintfoverstrcpy/strcat, andfgetsoverscanf("%s").
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write real C
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.
Count the vowels
Read a line of text (use fgets) and print how many vowels it contains - a, e, i, o, u in either case.
For Hello World print 3.
- Hello World
- Upper case
- No vowels
Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Reverse a word
Write void reverse(char *s) that reverses a string in place (swap characters from both ends toward the middle). main reads one word and prints it reversed.
For stressed print desserts.
- stressed
- Odd length
- Single character
Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Sign in to ask questions, help other learners, and earn XP for taking part.
Loading posts…