Learn how to declare, initialize, and access C arrays, with clear memory diagrams.
int a[5]; declares an array of 5a[0] to a[4]int a[] = {1,2,3};int m[3][4]sizeof(a)/sizeof(a[0]) for element countint a[5] = {10, 20, 30, 40, 50}; printf("%d\n", a[0]); // -> 10 printf("%d\n", a[4]); // -> 50
5 in int a[5] is the count. a[5] itself does not exist![5] means "how many" β reserves space for 5 elements.[ ] means "which one" β only 0 through 4 are valid.a[0] through a[4] β exactly 5 slots. Drill it in that the declaration count 5 and the last valid index 4 differ by one.a[5] or a[100] (often not even a warning). At runtime it may stomp on another variable, crash with a Segmentation fault, or β worst of all β appear to work while hiding a bug.i < 5 (strictly less) for "0 through 4." Writing i <= 5 would touch a[5] β the classic off-by-one error.
| Name | Type | Value |
|---|
type name[rows][cols];.// 3 rows x 4 columns int matrix[3][4] = { {1, 2, 3, 4}, // row 0 {5, 6, 7, 8}, // row 1 {9, 10, 11, 12} // row 2 };
matrix[1][2] is the third element of row 1 = 7.for (int i = 0; i < 3; i++) { // row for (int j = 0; j < 4; j++) { // column printf("%3d", matrix[i][j]); } printf("\n"); }
void func(int m[][4], int rows).Check your understanding of this lesson!
int a[5]; allocate?a[5] has 5 elements from a[0] to a[4].
C array indices always start at 0. For a[5], a[0] is the first element.
int a[3] = {1, 2};, what is the value of a[2]?When you partially initialize an array, the remaining elements are zero-initialized. a[2] is 0.
Combine this interactive site with books for more practice.
* Links above are affiliate links. Purchases help support this site.