In C, a string is used to store and work with text data such as names, messages, and sentences. Unlike some programming languages, C does not have a separate built-in string data type. Instead, strings are stored as arrays of characters terminated by a special null character \0.
A string is therefore a character array that represents text.
1. What is a String?
Strings are declared using character arrays. The size of the array determines the maximum number of characters the string can hold, including the trailing null terminator \0.
String Declaration Syntax
char string_name[size];
Example
char name[20]; // Stores up to 19 characters plus the null terminator '\0'
String Initialization
Strings can be initialized directly during declaration using a string literal. The compiler automatically adds the \0 character to the end.
char message[] = "Hello";
Memory Representation
Example Program
#include <stdio.h>
int main()
{
char message[] = "Hello";
printf("%s", message); // %s is the format specifier for strings
return 0;
}
How It Works
The string "Hello" is stored internally as a sequence of character bytes terminated by \0. When printf("%s", message) is called, the function reads characters sequentially from RAM starting at message[0] until it encounters the null character \0, which signifies the end of the string.
Console Output
Hello
2. Accessing Individual Characters
Because strings are standard character arrays under the hood, any individual character inside a string can be accessed or modified directly using zero-based array indexing.
Example Program
#include <stdio.h>
int main()
{
char name[] = "C Programming";
printf("%c", name[0]); // Accesses the very first character
return 0;
}
How It Works
Array indexing starts from 0. The compiler sets name[0] to store character 'C'. Calling printf("%c", name[0]) outputs only that singular character element.
Console Output
C
Important Points
Keep these critical rules in mind when programming with strings in C:
- Character Array Representation: C has no native "string" data type; strings are always arrays of characters.
- Mandatory Null Terminator: Strings must always end with
\0so standard C library functions can locate the string boundaries in memory. - Format Specifier: Use
%sinsideprintf()to output complete text strings, and%cto output single character variables.
Embedded Focus
In low-level embedded hardware, strings are crucial for debugging and telemetry. They represent the core data packets sent over serial communication lines (like UART, SPI, or USB) to report physical system states or output console logs using printf() redirection.
char uart_message[] = "Sensor Ready"; // Transmitted byte-by-byte over UART Tx pin
Because microcontrollers are memory-constrained, handling strings inefficiently can quickly consume limited RAM. Embedded engineers often store constant strings in Program Memory (Flash) instead of working RAM to optimize memory resource allocation.