Chapter 13: Arrays and Strings
Arrays and strings are the most basic data structures in C. Unlike higher-level languages, C provides no built-in "string type." Instead, strings are simply arrays of characters that follow a specific convention.
I. Array Basics
An array is a collection of elements of the same type stored in contiguous memory.
- Declaration:
int arr[5]; - Initialization:
int arr[] = {1, 2, 3, 4, 5}; - Indexing:
arr[0]is the first element,arr[4]is the last.
The Contiguous Memory Guarantee
Because elements are guaranteed to be side-by-side in RAM, the CPU can cache them efficiently, making array access incredibly fast.
II. Multidimensional Arrays
Arrays of arrays are stored in Row-Major Order in memory—the first row, then the second row, etc.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
// Memory layout: 1, 2, 3, 4, 5, 6
III. The C String Convention
In C, a string is a char array that ends with the Null Terminator (\0). This character (ASCII 0) tells the standard library functions (like printf or strlen) where the string ends.
char name[] = "C Lang";
// Memory: 'C', ' ', 'L', 'a', 'n', 'g', '\0'
Buffer Overflow Risk
C does not check array boundaries. If you copy a 20-character string into a 10-character array, you will overwrite adjacent memory, leading to crashes or security vulnerabilities.
IV. String Operations (<string.h>)
| Function | Action | Warning |
|---|---|---|
strlen(s) | Get string length | Excludes the \0 |
strcpy(dest, src) | Copy string | Unsafe (no length check) |
strncpy(dest, src, n) | Safe copy | Limits to n chars |
strcat(dest, src) | Append string | Unsafe |
strcmp(s1, s2) | Compare strings | Returns 0 if equal |
#include <string.h>
char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, " ");
strcat(str1, str2);
printf("%s (len: %zu)\n", str1, strlen(str1));
V. Character Arrays vs. String Literals
char arr[] = "hello";: The string is copied onto the Stack. You can modify it.char *ptr = "hello";: The string lives in the Text Segment (read-only). Modifying it causes a Segmentation Fault.
VI. Modern String Safety
Always prefer the "n" versions of string functions (strncpy, strncat, snprintf). They require you to specify the destination buffer size, preventing most buffer overflow attacks.