In the last lesson, Arrays in C: Storing Many Values Under One Name, you stored many numbers under one name in an array. A string is the same idea: an array of char, one character in each box. Every variable so far has held a number, but programs work with text all the time: names, cities, answers. In this lesson you store one character, then a whole word, then read a name from the keyboard and break it on purpose. Along the way you find out what the \0 escape sequence from the printf lesson is for, and meet the input buffer from Using Library Functions: #include, getch(), and the Input Buffer again.
In this lesson you will
- Store a single character in a
charvariable and print it with%c - Store a word as a string: a row of characters ending in
'\0' - Print a string with
%sand read one withscanf, and find out why it stops at a space - Read a whole line safely with
fgets, and spot the Enter key it keeps - Use
strlenandstrcpyfromstring.h, and learn why=cannot copy a string
Start a new project for this lesson. Copy 004-ArraysCProgram to a new folder named 005-StringsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.
Try it: one character
The data-type table in the int vs float lesson listed char, a type that holds a single character, printed with %c. Try it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char initial = 'K';
printf("Your initial is %c\n", initial);
return 0;
}
Your initial is K
Notice the single quotes. 'K' is a character literal: exactly one character. Double quotes make a string literal, which can hold many. Change 'K' to "K" and the build complains. Change it back.
Try it: a whole word
A char holds one character, so a name needs a whole row of them. Replace main with this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[20] = "Ken";
printf("Hello, %s!\n", name);
printf("Letters: %c %c %c\n", name[0], name[1], name[2]);
printf("After the last letter: %d\n", name[3]);
name[0] = 'B';
printf("Hello, %s!\n", name);
return 0;
}
Hello, Ken! Letters: K e n After the last letter: 0 Hello, Ben!
What just happened
char name[20] declares an array, just like int scores[5] in the arrays lesson, except that each of its 20 boxes holds a char instead of an int. You reach each one by its index in square brackets, and counting still starts at 0, so name[0] is the first character and name[19] is the last.
Initialising the array with "Ken" fills it like this:
| Index | 0 | 1 | 2 | 3 | 4 to 19 |
|---|---|---|---|---|---|
| Contents | 'K' | 'e' | 'n' | '\0' | '\0' (unused) |
Straight after the last letter sits '\0', the null character. Printed as a number with %d, it shows as 0. This is the end marker that the escape-sequence table promised to explain: in C, a string is a row of characters that ends with '\0'. %s tells printf to start at the first character and keep printing until it reaches the '\0'. Changing name[0] to 'B' changed one box, so the whole word became Ben.
Because the end marker takes up one place, an array of 20 characters can hold a string of at most 19 characters.
Try it: ask for the name
Now let the user type the name. scanf reads a string with %s:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[20] = "";
char colour[20] = "";
printf("What is your name?\n");
scanf("%s", name);
printf("What is your favourite colour?\n");
scanf("%s", colour);
printf("Hello, %s! Your favourite colour is %s.\n", name, colour);
return 0;
}
Build and run. Type Ken and press Enter, then type blue and press Enter:
What is your name? Ken What is your favourite colour? blue Hello, Ken! Your favourite colour is blue.
Look closely: there is no & in front of name. In the scanf lesson, scanf needed &x, the location of the variable. The name of an array already stands for the location of its first character, so name on its own is enough. Add an & out of habit and GCC warns:
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat=]
If you tried that, remove the & again and rebuild.
Break it on purpose: type a name with a space
Run the program again. At the first question type Ken Smith and press Enter. Observe: the program does not wait for the colour. It answers straight away:
What is your name? Ken Smith What is your favourite colour? Hello, Ken! Your favourite colour is Smith.
Your surname has become your favourite colour.
%s in scanf reads one word. It stops at the first space, tab or Enter. So name got Ken, and the rest of the line, Smith and the Enter, stayed behind in the input buffer, the same waiting area that caught the held-down key in the previous lesson. The second scanf found Smith already waiting and took it without asking.
Try it: read the whole line with fgets
To read everything the user typed, up to and including the Enter, use fgets (“file get string”). Here the “file” is stdin, the standard input, which is normally the keyboard. The program also uses strlen (“string length”), which counts the characters before the '\0'. It is declared in string.h, so the program includes that header:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[20] = "";
printf("What is your full name?\n");
fgets(name, sizeof(name), stdin);
int length = strlen(name);
printf("Hello, %s!\n", name);
printf("Your name has %d characters.\n", length);
return 0;
}
Run it and type Ken Smith. Observe two odd things:
What is your full name? Ken Smith Hello, Ken Smith ! Your name has 10 characters.
The ! has dropped onto the next line, and Ken Smith has 9 characters (the space counts), not 10. Both clues point to the same thing: fgets keeps the Enter key. The string in memory is Ken Smith\n. That hidden \n is the tenth character, and printing it moves the ! to a new line.
fgets takes three things: where to store the text, the size of the array (sizeof(name), here 20), and where to read from (stdin). Because it knows the size, it stores at most 19 characters plus the '\0'.
To remove the Enter, add one line after the fgets. strcspn(name, "\n"), also from string.h, counts the characters before the first \n, which is exactly the index where the \n sits. Putting '\0' there ends the string one place earlier. Rebuild and run with Ken Smith again:
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; /* remove the Enter */
What is your full name? Ken Smith Hello, Ken Smith! Your name has 9 characters.
Now try a long name, such as Alexandria Montgomery-Smith. The program prints Hello, Alexandria Montgome! (19 characters). fgets stopped when the array was full and left the rest in the input buffer. Cut off, but safe.
Why the size matters: buffer overflow. scanf("%s", name) does not know how big name is. Type more than 19 characters and it writes past the end of the array, over whatever memory comes next. This is a buffer overflow. The program may crash, quietly change other variables, or work on one computer and fail on another, and attackers use overflows to break into systems. fgets is given the size, so it cannot overflow. (Old books mention a function called gets. It has the same problem and has been removed from C. Never use it.)
Try it: give the string a new value
You can set a number with = at any time, so it seems natural to do the same with a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[20] = "Ken";
printf("Before: %s\n", name);
name = "Kenneth";
printf("After: %s\n", name);
return 0;
}
Break it on purpose: copy a string with =
Build it. The build stops with:
main.c:10:10: error: assignment to expression with array type
= worked in the declaration, char name[20] = "Ken";, because that is initialisation: the array is filled as it is created. Afterwards, C does not let you assign a whole array with =.
To copy text into an existing array, use strcpy (“string copy”) from string.h. It copies the characters one by one, including the '\0'. Replace the = line with:
strcpy(name, "Kenneth");
Before: Ken After: Kenneth
Read strcpy(name, "Kenneth") as “copy "Kenneth" into name”: the destination comes first, like the left side of =. Like scanf("%s"), strcpy does not check the size, so the destination must be big enough.
Key terms
char: a data type that holds a single character, printed with%c.- Character literal: one character in single quotes, such as
'K'. - Array: a row of variables of the same type under one name, such as
char name[20]. - Index: the position of an item in an array, counted from 0, as in
name[0]. - String: in C, a row of characters in a
chararray, ending with'\0'. - Null character (
'\0'): the character with value 0 that marks the end of a string. %s: the format specifier for a string, in bothprintfandscanf.fgets: reads a whole line of input, up to a size limit, and keeps the Enter (\n).strlen: astring.hfunction that counts the characters in a string, not including the'\0'.- Buffer overflow: writing past the end of an array, into memory that belongs to something else.
Quick check
How big must a
chararray be to hold the string"Hello"?Show answer
At least 6: five letters plus the
'\0'at the end.A program uses
scanf("%s", city);and the user typesPort of Spain. What ends up incity, and where is the rest?Show answer
Port.%sstops at the first space, andof Spainplus the Enter wait in the input buffer for the next read.After
fgets(name, sizeof(name), stdin)readsAna,strlen(name)says 4. Why?Show answer
fgetskeeps the Enter, so the string isAna\n. Remove it withname[strcspn(name, "\n")] = '\0';city = "Paris";givesassignment to expression with array type. How do you fix it?Show answer
Use
strcpy(city, "Paris");and add#include <string.h>. Arrays cannot be assigned with=after they are declared.
Part of the Introduction to C series. Next: Storing Records with Parallel Arrays
Updates
2026/10/07
– Moved after the new Arrays lesson and added a link back to it.
[…] Part of the Introduction to C series. Next: Strings in C: char Arrays, %s, fgets, and strlen […]
[…] Strings in C: char Arrays, %s, fgets, and strlen you stored a name in a char array, and in the arrays lesson before it you stored five scores in an […]