C Strings — Character Arrays, strlen, and Safe Input
Learning Objectives
- Represent text using character arrays in C
- Explain the role of the null terminator
- Measure and manipulate strings with standard functions
- Read text input safely without overflowing buffers
How C Represents Text
A C string is an array of characters ending with a special sentinel called the null character. That terminator has the numeric value zero and marks where the text stops. Without it, functions that expect a string would keep scanning past your data into unrelated memory.
char greeting[] = "Hello";
char letters[6] = {'H', 'e', 'l', 'l', 'o', 0};
Both forms describe five visible characters plus the terminator. When you use a double-quoted literal, the compiler adds the terminator for you. If you fill the array manually, remember to reserve one extra byte for it.
| Item | Meaning |
|---|---|
| Null terminator | Zero byte marking the end of text |
| strlen | Counts characters before the terminator |
| Buffer | Fixed-size array that stores the text |
| Overflow | Writing past the reserved buffer size |
Measuring and Printing
The standard library provides helpers declared in the string header. strlen returns the number of characters excluding the terminator. printf with a string specifier prints until the terminator is reached.
#include
#include
int main(void) {
char name[] = "Ada";
printf("%s\n", name);
printf("Length: %zu\n", strlen(name));
return 0;
}
Because strlen counts only visible characters, an array of four bytes holding Ada has length three. Understanding that difference prevents off-by-one errors when you allocate buffers or copy text.
Copying and Concatenating
You cannot assign one array to another with the equals sign in C. That syntax will not copy the characters. Use dedicated functions that copy bytes and preserve the terminator.
#include
#include
int main(void) {
char source[] = "Learn C";
char dest[20];
strcpy(dest, source);
strcat(dest, " today");
printf("%s\n", dest);
return 0;
}
strcpy writes the source text into the destination buffer. strcat appends to the end of an existing string by finding the terminator and overwriting it with the new content plus a fresh terminator. Both functions require that the destination has enough room.
Safer variants that accept an explicit limit let you cap how many bytes are written. Adopting them early builds good defensive habits.
Reading Strings Safely
Plain scanf with a string specifier stops at whitespace and does not limit length by itself unless you add a field width. Without a width, a long name can overflow the buffer and corrupt adjacent memory.
char city[32];
printf("Enter a city: ");
scanf("%31s", city);
printf("City: %s\n", city);
The width thirty-one leaves room for thirty characters plus the terminator. Another common approach is to use the fgets function, which reads an entire line up to a size you provide and always terminates safely.
char line[100];
printf("Enter a phrase: ");
fgets(line, sizeof(line), stdin);
fgets may keep the newline character at the end of the input. You can strip it with a small loop or string function when clean text is required for comparison.
⚠️Never Trust Unbounded Input
Any function that writes into a fixed buffer must receive a maximum size. Unchecked input is one of the classic routes to buffer overflow vulnerabilities in C programs.
Common String Tasks
Beginners benefit from practicing a handful of core tasks: reverse a string in place, count vowels, compare two strings for equality with the string compare function, and convert case. Each task reinforces indexing, terminators, and loop bounds.
Remember that comparing with equals checks whether two arrays hold the same address, not the same characters. Always use the library comparison function for text equality.
Key Takeaways
💡
- C strings are character arrays finished with a null terminator
- strlen measures characters but not the terminator byte
- Arrays cannot be assigned element text with a plain equals sign
- Always reserve room for the terminator when sizing buffers
- Use width-limited input or fgets to prevent buffer overflow
Practice Questions
- Why does the string Hello require six bytes of storage?
- What does strlen return for a string of ten characters?
- How does a field width in a scanf call protect against overflow?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions