Nearby lessons

42 of 72

C - 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.

Example01
Loading editor…

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.

Example02
Loading editor…

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.

Example03
Loading editor…

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.

Example04
Loading editor…

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. Use fgets() instead.
  • Accessing characters outside the valid array indexes.
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.