Nearby lessons
42 of 72C - String Introduction
Learn what a string is in C, how to declare and initialize strings, and how to read and display strings using simple examples.
What Is a String?
A string is a collection of characters. In C, we store strings using character arrays.
For example, "Hello" is a string containing five letters.
C adds a special character called the null character (\0) at the end of a string initialized using a string literal.
Declaring and Initializing a String
We can declare a character array and assign a string to it.
Example: char name[20] = "Rahul";
The array has space for 20 characters, including the ending null character.
Understanding the Null Character
The null character (\0) tells C where a string ends.
The string "Hello" contains five letters and one null character. Therefore, it needs six character positions when stored as a string.
Displaying Characters Using a Loop
We can use a loop to display each character of a string one by one. The loop stops when it reaches \0.
Common Mistakes
- Forgetting to leave space for the ending null character.
- Expecting
scanf("%s", name)to read a full name with spaces. - Using
gets(), which is unsafe. Usefgets()instead. - Accessing characters outside the valid array indexes.
- C stores strings using character arrays.
- The null character (\0) marks the end of a string.
- A string needs space for its characters and the null character.
- scanf("%s", name) reads only one word.
- fgets() can read a line containing spaces.