These are the notes for C episode 9. Until now our programs only worked with numbers. Here you learn to work with text: a customer's name, a coupon code, a message. In C, a piece of text is called a string, and it is nothing new: it is an array of char (episode 8) with one hidden character at the end. You will learn why a single char can't hold a name, the null character '\0' and why printf needs it, string literals, reading text with scanf and fgets, removing the newline that fgets keeps, the crash when input is too long (stack smashing), and the string.h functions strlen, strcpy, strcat and strcmp. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.
The problem: a name on the bill
Bhaiya's chai stall prints bills with only numbers. His regular customers want to see their name: Customer: Ravi. We know one type for text, char from episode 2, which holds one letter in single quotes ('R'). So the obvious attempt is:
#include <stdio.h>
int main() {
char name = "Ravi";
printf("Customer: %c\n", name);
return 0;
}
gcc says:
main.c: In function 'main':
main.c:4:17: warning: initialization of 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
4 | char name = "Ravi";
| ^~~~~~
And the output is Customer: followed by one junk character. No Ravi.
Why it failed: a char is one box for one letter. "Ravi" is four letters; it simply doesn't fit. (The warning mentions char *, a pointer: text in double quotes is really an address. That is next episode's topic.)
The fix: a name is a row of letters, so store it in a row of
charboxes: an array.
The fix: an array of letters
Think of a name bracelet: each bead carries one letter (a char), and the beads on one thread make the name (an array of char). It's a normal array, so name[0] is the first letter.
#include <stdio.h>
int main() {
char name[4] = {'R', 'a', 'v', 'i'};
for (int i = 0; i < 4; i++) {
printf("%c", name[i]);
}
printf("\n");
return 0;
}
Output:
Ravi
It works, but writing a loop for every name is tiring. printf has %s to print a whole string at once. Let's try it.
Where does the text end? The null character '\0'
Our program also stores a coupon code in a second array:
#include <stdio.h>
int main() {
char name[4] = {'R', 'a', 'v', 'i'};
char code[7] = "SAVE10";
printf("Customer: %s\n", name);
printf("Coupon: %s\n", code);
return 0;
}
Output:
Customer: RaviSAVE10
Coupon: SAVE10
The coupon leaked into the name, with no error and no warning.
Why: printf is a function, and (as we saw in episode 8) a function receives only where an array starts, not its size. So %s prints letter after letter until it finds a stop sign. Our name had no stop sign, so printf kept going into the next thing in memory, which happened to be the coupon.
memory: R a v i S A V E 1 0 \0
└ name ─┘ └──── code ───────┘
The stop sign is the null character, written '\0' (backslash zero). Its value is 0. Every string in C must end with '\0'. Think of it as the knot at the end of the bracelet's thread: without it, the beads slide off into the next bracelet.
The knot needs space: a 4-letter name needs 5 slots.
char name[5] = {'R', 'a', 'v', 'i', '\0'};
Output:
Customer: Ravi
Coupon: SAVE10
printf stopped at the knot.
String literals: double quotes tie the knot for you
Text in double quotes, like "Ravi", is a string literal, and C adds the '\0' automatically. With empty brackets C also counts the size for you:
#include <stdio.h>
int main() {
char name[] = "Ravi";
printf("Size: %zu\n", sizeof(name));
for (int i = 0; name[i] != '\0'; i++) {
printf("name[%d] = %c\n", i, name[i]);
}
return 0;
}
Output:
Size: 5
name[0] = R
name[1] = a
name[2] = v
name[3] = i
sizeof(name)is 5: four letters plus the null character.- The loop runs until
name[i]is'\0', so it works for a name of any length. This is how every string function works inside.
| Written as | Type | Size |
|---|---|---|
'R' (single quotes) |
one char |
1 byte |
"R" (double quotes) |
a string: 'R' + '\0' |
2 bytes |
"Ravi" |
a string | 5 bytes |
A string = an array of char that ends with '\0'. You just invented strings.
Walking through a string: capitals on the bill
Because a string is an array, you can visit every character with a loop and even change it. The loop does not need the length: it stops at the '\0'. Bhaiya's bill printer looks best with names in capitals, so we use toupper from <ctype.h> (it turns a small letter into a capital and leaves everything else alone), and count the spaces on the way to count the words.
#include <stdio.h>
#include <ctype.h>
int main() {
char name[] = "Ravi Kumar";
int spaces = 0;
for (int i = 0; name[i] != '\0'; i++) {
name[i] = toupper(name[i]);
if (name[i] == ' ') spaces++;
}
printf("%s\n", name);
printf("Words: %d\n", spaces + 1);
return 0;
}
Output:
RAVI KUMAR
Words: 2
name[i] != '\0'is the standard way to walk a string of any length.toupper('a')gives'A';toupper(' ')gives' 'unchanged. Its partnertolowerdoes the opposite.
Reading a name: scanf("%s") and fgets
The name should come from the keyboard. scanf with %s reads a word. Notice: no & before name. (Why an array needs no & is the big reveal of episode 10.)
#include <stdio.h>
int main() {
char name[20];
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
Input Ravi Kumar, output:
Hello, Ravi!
Kumar vanished: %s stops reading at the first space (or Tab or Enter).
To read a whole line, use fgets(where, how_much_room, stdin). stdin means "standard input", the keyboard. Let's also print the length with strlen from string.h:
#include <stdio.h>
#include <string.h>
int main() {
char name[20];
fgets(name, sizeof(name), stdin);
printf("Hello, %s!\n", name);
printf("Length: %zu\n", strlen(name));
return 0;
}
Input Ravi Kumar (then Enter), output:
Hello, Ravi Kumar
!
Length: 11
The ! jumped to the next line and the length is 11, not 10: fgets keeps the Enter key, the newline '\n', at the end of the string.
One line removes it. strcspn(name, "\n") returns the position of the first '\n' (or the length, if there is none), and we put the null character there:
name[strcspn(name, "\n")] = '\0';
Full program output with the same input:
Hello, Ravi Kumar!
Length: 10
scanf("%s", s) |
fgets(s, sizeof(s), stdin) |
|
|---|---|---|
| Reads | one word (stops at a space) | a whole line, spaces included |
| Keeps the Enter? | no | yes: trim it with strcspn |
| Size limit | only if you write one: %19s |
always (the second argument) |
When the name is too long: buffer overflow
A small array has room for 4 letters, and the customer is called Venkataraman (12 letters):
#include <stdio.h>
int main() {
char name[5];
scanf("%s", name);
printf("Hello, %s\n", name);
return 0;
}
Input Venkataraman, output:
*** stack smashing detected ***: terminated
scanf doesn't know the array's size. It kept writing past the end of name, over memory that isn't ours. The system detected the damage and killed the program. Writing past the end of an array is called a buffer overflow; in real software it's a classic security hole.
The fix: always give a limit. %4s reads at most 4 characters, leaving room for '\0' (the limit is always the size minus one):
scanf("%4s", name);
Output:
Hello, Venk
Cut short, but safe. With fgets, the sizeof(name) you pass does the same job.
Copying and joining strings: strcpy and strcat
The next customer is Amit. The obvious way, name = "Amit";:
#include <stdio.h>
int main() {
char name[20] = "Ravi";
name = "Amit";
printf("%s\n", name);
return 0;
}
main.c: In function 'main':
main.c:5:10: error: assignment to expression with array type
5 | name = "Amit";
| ^
The same error as episode 8: a string is an array, and arrays can't be assigned with =. (char name[20] = "Ravi"; is allowed because that is initialisation, at creation.)
<string.h> has ready-made functions that do the letter-by-letter loop for you:
#include <stdio.h>
#include <string.h>
int main() {
char name[20] = "Ravi";
strcpy(name, "Amit");
char greet[30] = "Mr. ";
strcat(greet, name);
printf("%s\n", greet);
printf("Length: %zu\n", strlen(greet));
return 0;
}
Output:
Mr. Amit
Length: 8
| Function | What it does | Example |
|---|---|---|
strlen(s) |
number of characters before '\0' |
strlen("Mr. Amit") → 8 |
strcpy(dest, src) |
copies src into dest, '\0' included |
strcpy(name, "Amit") |
strcat(dest, src) |
joins src onto the end of dest |
"Mr. " + "Amit" |
strcmp(a, b) |
compares letter by letter, 0 if equal | next section |
strcspn(s, chars) |
position of the first character from chars |
trimming '\n' |
Warning: strcpy and strcat don't check sizes either. The destination must have room for the result plus '\0', or you get the same overflow as above.
Comparing strings: strcmp, never ==
Bhaiya starts a coupon: SAVE10 gives 10% off. We check it with ==, like numbers in episode 5:
#include <stdio.h>
int main() {
char coupon[10];
scanf("%9s", coupon);
if (coupon == "SAVE10") {
printf("10%% off!\n");
} else {
printf("Invalid coupon\n");
}
return 0;
}
Input SAVE10 (typed perfectly), output:
Invalid coupon
No error, no warning (with this command line). == on arrays compares where they are in memory, not the letters inside. coupon and the literal "SAVE10" live in two different places, so they are never equal.
strcmp(a, b) compares letter by letter and returns 0 when the strings match:
#include <stdio.h>
#include <string.h>
int main() {
char coupon[10];
scanf("%9s", coupon);
if (strcmp(coupon, "SAVE10") == 0) {
printf("10%% off!\n");
} else {
printf("Invalid coupon\n");
}
return 0;
}
Input SAVE10, output:
10% off!
If the strings differ, strcmp returns a negative number when a comes first in dictionary (character-code) order, and a positive number when a comes later:
printf("%d %d %d\n", strcmp("abc", "abc"), strcmp("abc", "abd") < 0, strcmp("b", "a") > 0);
0 1 1
Comparison is case-sensitive: "save10" is not "SAVE10". (%% in printf prints one % sign.)
Your string.h toolbox
| Function | What it does | Example |
|---|---|---|
strlen(s) |
Counts the characters before '\0' |
strlen("chai") → 4 |
strcpy(dst, src) |
Copies src (with its '\0') into dst |
strcpy(name, "Amit") |
strcat(dst, src) |
Joins src onto the end of dst |
strcat(greet, name) |
strcmp(a, b) |
0 if equal, negative if a comes first, positive if b does |
strcmp(coupon, "SAVE10") == 0 |
None of them checks sizes: the destination must have room for the result plus the '\0'.
Common mistakes (and the real gcc messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
char name = "Ravi"; |
warning: initialization of 'char' from 'char *' makes integer from pointer without a cast |
A char holds one letter |
char name[] = "Ravi"; |
char name[4] = {'R','a','v','i'}; then %s |
No error: RaviSAVE10, extra junk |
No room for '\0' |
char name[5] with '\0', or char name[] = "Ravi" |
scanf("%s", name) with a long name |
*** stack smashing detected ***: terminated |
Writes past the array | %4s, or fgets(name, sizeof(name), stdin) |
scanf("%s") for a full name |
No error: only the first word | %s stops at a space |
fgets |
fgets without trimming |
No error: output breaks onto a new line, length one too big | fgets keeps the '\n' |
name[strcspn(name, "\n")] = '\0'; |
name = "Amit"; |
error: assignment to expression with array type |
Arrays can't be assigned | strcpy(name, "Amit"); |
if (coupon == "SAVE10") |
No error: always false | == compares addresses |
strcmp(coupon, "SAVE10") == 0 |
if (strcmp(a, b)) meaning "equal" |
No error: logic reversed | strcmp returns 0 for equal |
strcmp(a, b) == 0 |
Mini project: a bill with the customer's name and a coupon
#include <stdio.h>
#include <string.h>
int main() {
char name[30], coupon[10];
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
scanf("%9s", coupon);
int bill = 250;
printf("Customer: %s (%zu letters)\n", name, strlen(name));
if (strcmp(coupon, "SAVE10") == 0) {
bill = bill - bill * 10 / 100;
printf("Coupon %s applied\n", coupon);
} else {
printf("Coupon %s not valid\n", coupon);
}
printf("To pay: Rs %d\n", bill);
return 0;
}
Input:
Priya Sharma
SAVE10
Output:
Customer: Priya Sharma (12 letters)
Coupon SAVE10 applied
To pay: Rs 225
With a wrong coupon (Priya Sharma then FREE50):
Customer: Priya Sharma (12 letters)
Coupon FREE50 not valid
To pay: Rs 250
fgetsreads the full name (with the space) andstrcspntrims the Enter.%9sreads at most 9 characters intocoupon[10].strlencounts 12 characters: the space counts too.strcmp(...) == 0checks the coupon letter by letter.
Practice
- Read a name and print it backwards.
- Count the vowels in a sentence read with
fgets. - Write your own
int my_strlen(char s[])with a loop. - Ask for a password until
strcmpsays it matches. - Why does
char s[4] = "chai";compile but print junk with%s?
Solutions
1. Backwards (verified, input Ravi):
#include <stdio.h>
#include <string.h>
int main() {
char name[30];
scanf("%29s", name);
for (int i = strlen(name) - 1; i >= 0; i--) {
printf("%c", name[i]);
}
printf("\n");
return 0;
}
ivaR
2. Vowels (input One masala chai please):
#include <stdio.h>
int main() {
char line[100];
fgets(line, sizeof(line), stdin);
int vowels = 0;
for (int i = 0; line[i] != '\0'; i++) {
char c = line[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowels++;
}
}
printf("Vowels: %d\n", vowels);
return 0;
}
Vowels: 10
3. my_strlen: walk until the null character.
#include <stdio.h>
int my_strlen(char s[]) {
int n = 0;
while (s[n] != '\0') {
n++;
}
return n;
}
int main() {
printf("%d\n", my_strlen("chai"));
printf("%d\n", my_strlen("Priya Sharma"));
printf("%d\n", my_strlen(""));
return 0;
}
4
12
0
4. Password (inputs samosa, lassi, chai123):
#include <stdio.h>
#include <string.h>
int main() {
char pass[20];
do {
printf("Password: ");
scanf("%19s", pass);
if (strcmp(pass, "chai123") != 0) {
printf("Wrong, try again\n");
}
} while (strcmp(pass, "chai123") != 0);
printf("Welcome, bhaiya!\n");
return 0;
}
Password: Wrong, try again
Password: Wrong, try again
Password: Welcome, bhaiya!
(The typed input doesn't appear in the output because it comes from the input box, not the terminal.)
5. C allows a literal to fill an array exactly, but then there is no slot left for '\0', so the array is not a string. %s runs past the end. Use char s[5] or char s[].
Quick quiz
What does this print?
char s[] = "chai";
printf("%zu %zu", sizeof(s), strlen(s));
- A.
4 4 - B.
5 4 - C.
4 5 - D.
5 5
Answer
B: 5 4 (verified). sizeof counts every slot, including the '\0' the double quotes add. strlen counts only the characters before the '\0'.
Interview questions
- How is a string represented in C?
- What is the null character and why is it needed?
- What is the difference between
'A'and"A"? - What is the difference between
sizeofandstrlenfor a string? - Why can't you compare two strings with
==? What doesstrcmpreturn? - Why can't you assign a string with
=? How do you copy one? - What is the difference between
scanf("%s")andfgets? Why isgetsbanned? - What is a buffer overflow, and how do you prevent it when reading input?
- Why does
scanf("%s", name)not need&? (Answered in episode 10.)
Glossary
| Term | Meaning | Example |
|---|---|---|
| String | Text: an array of char ending in '\0' |
char name[] = "Ravi"; |
char array |
An array whose slots each hold one character | char name[20]; |
Null character '\0' |
The character with value 0 that marks where a string ends | the 5th slot of "Ravi" |
| String literal | Text in double quotes; C adds the '\0' |
"SAVE10" |
| Character literal | One character in single quotes | 'R' |
%s |
printf/scanf specifier for a string |
printf("%s", name) |
| Width limit | A number in %s that caps how much is read |
%4s |
stdin |
Standard input: the keyboard / input box | fgets(s, 20, stdin) |
fgets |
Reads a whole line, up to a size limit, keeping the newline | fgets(name, sizeof(name), stdin) |
Newline '\n' |
The character the Enter key produces | kept by fgets |
string.h |
Header with the string functions | #include <string.h> |
strlen |
Counts characters before '\0' |
strlen("chai") → 4 |
strcpy |
Copies one string into another | strcpy(name, "Amit") |
strcat |
Joins one string onto the end of another | strcat(greet, name) |
strcmp |
Compares two strings; 0 means equal | strcmp(a, b) == 0 |
strcspn |
Position of the first character from a set | strcspn(name, "\n") |
| Initialisation | Giving a variable or array a value when it is created | char s[] = "hi"; |
| Buffer | An array used to hold data, like input text | char name[5] |
| Buffer overflow | Writing past the end of a buffer | 12 letters into name[5] |
| Stack smashing | gcc's protection noticing an overflow and stopping the program | *** stack smashing detected *** |
toupper |
From <ctype.h>: turns a small letter into a capital |
toupper('r') → 'R' |
ctype.h |
Header with character functions (toupper, tolower, isdigit ...) |
#include <ctype.h> |
| Case-sensitive | Capital and small letters are different | "save10" ≠ "SAVE10" |
Summary
- A string is an array of
charending in'\0'; double quotes add the'\0'for you, so a string needs one slot more than its letters. %sprints until'\0'; without it,printfruns into the next thing in memory.scanf("%s")reads one word;fgetsreads a whole line but keeps the Enter (trim it withstrcspn).- Always limit input (
%4s,sizeof), or a long input overflows the array: stack smashing. - Strings can't be assigned with
=or compared with==: usestrcpy,strcat,strlenandstrcmp(a, b) == 0from<string.h>.
Next episode: pointers. Two mysteries are still open: why does scanf need & for a number but not for a string, and why could a function change main's array but not main's int? The answer is addresses.