Nearby lessons
62 of 124C - Strings (Character Arrays)
Strings (Character Arrays) is one of the foundational topics in C programming. This lesson explains What is a String in C?, Declaring and Initializing Strings and Reading Strings — scanf, gets, fgets with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
What is a String in C?
In C, a string is simply an array of characters ending with a special character '\0' (called the null character). This \0 tells C where the string ends.
So a string "Rahul" needs an array of size at least 6 (5 characters + the \0). This is a common beginner mistake — forgetting space for the null character.
In simple words: a string is just a row of characters with a full-stop marker — \0 — at the end. The \0 is invisible; it only tells C "the text ends here".
Trainer's Note: Memory trick: `\0` is not the digit 0 and not the letter O — it is one character that means "end of text". Count it whenever you size a char array: text length + 1.
Example01
Declaring and Initializing Strings
Trainer's Note: "Rahul" (double quotes) is a string — it ends with \0. 'A' (single quotes) is a single character — it has no \0. Do not mix them.
Example02
Reading Strings — scanf, gets, fgets
| Function | Reads | Limitation |
|---|---|---|
| scanf("%s", name) | One word (no spaces) | Stops at the first space |
| gets(name) | A whole line including spaces | Unsafe (no size check) — avoid |
| fgets(name, size, stdin) | A whole line, safely | The modern safe choice |
Trainer's Note: scanf with %s reads only one word — "Rahul Kumar" would store only "Rahul". To read a full line with spaces, use fgets() (modern and safe). The old textbook's gets() is dangerous because it does not check the size — it can overflow memory. Prefer fgets.
Example03
String Basics Without Functions
Understand how it works underneath by doing it with loops (the classic exam approach):
Example04
📝 Key Takeaways
- A string = char array + a null character '\0' at the end.
- Remember to leave room for '\0' when sizing arrays.
- scanf %s reads one word; fgets reads a full line safely.
- Use string.h functions: strlen, strcpy, strcat, strcmp.
- Never use = or == for strings — use strcpy and strcmp.
- Loops can count, reverse and check strings from scratch.
🧠 Test Your Knowledge
5 QuestionsProgress: 0 / 5