In the C programming language, strings are not primitive data types; they are null-terminated arrays of characters (char[]). Initializing strings correctly requires understanding the critical distinction between stack-allocated mutable character arrays and read-only string literals stored in ELF .rodata memory segments.
String Initialization Syntax Comparison
#include <stdio.h>
#include <string.h>
int main(void) {
// 1. Stack Array Initialization (Mutable)
char str1[] = "Hello Lynxbee"; // Compiler auto-sizes to 14 bytes (13 chars + '\0')
// 2. Explicit Fixed-Size Stack Array
char str2[20] = "Embedded C"; // Bytes 11-19 auto-zero-padded to '\0'
// 3. Character List Array Initialization
char str3[] = {'C', 'o', 'd', 'e', '\0'}; // Must include explicit '\0'!
// 4. Pointer to String Literal (IMMUTABLE - Stored in .rodata)
const char *str4 = "Read Only Segment"; // Attempting str4[0] = 'X' causes Segmentation Fault!
printf("str1: %s (size: %zu)\n", str1, sizeof(str1));
printf("str4: %s (length: %zu)\n", str4, strlen(str4));
return 0;
}
Comments and corrections