Back to course

Introduction to Strings (Character Arrays)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 30: Introduction to Strings (Character Arrays)

In C, there is no built-in String type. A string is defined as a one-dimensional array of characters terminated by a special null character (\0).

Null Termination (\0)

The null character signals the end of the string. Functions that process strings (like printf with %s) rely on finding this terminator.

String Declaration and Initialization

1. Character Array Initialization (Manual)

We must explicitly include the null terminator.

c char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Requires size 6 for 5 characters + null terminator

2. String Literal Initialization (Recommended)

Using double quotes automatically adds the null terminator (\0).

c char greeting[] = "Hello"; // Compiler calculates size as 6

// If we define size explicitly, ensure it is big enough: char city[10] = "Paris"; // Size 10 allocated, 'Paris' takes 6 (5 + \0)

Reading Strings

Using scanf()

scanf() stops reading input when it encounters whitespace (space, newline, tab). Note that we do not use & when reading an array name.

c char first_name[20]; printf("Enter first name: "); scanf("%s", first_name); // Reads only one word

Using fgets() (Recommended for security)

fgets() is safer because it prevents buffer overflows by allowing you to specify the maximum size. It reads until a newline or the size limit is reached.

c char full_name[50]; printf("Enter full name: "); // Reads up to 49 characters from stdin and stores in full_name fgets(full_name, 50, stdin);