Arrays (Single & Multi-Dimensional)
Arrays allocate a contiguous block of memory to store values of a single data type. In C, arrays do not support dynamic boundary validation checks, making safety crucial.
1 Contiguous Memory & Out-Of-Bounds Risks
Because C arrays store elements contiguously (one directly after another in memory), accessing index elements is very fast. However, **C does not validate array boundaries.** If you declare `int arr[5];` and attempt to assign `arr[10] = 50;`, the compiler will allow it. At runtime, this writes directly to random heap/stack memory offsets, causing data corruption, silent bugs, or crashes (Segmentation Faults).
2 Matrices and Array Initializations
Let's run a program establishing single arrays, double matrices, and iterating values:
C — Arrays & Iterating Matrices
▶ Run Code
#include <stdio.h>
int main() {
// Array initialization
int scores[5] = {90, 85, 78, 92, 88};
printf("First score: %d\n", scores[0]);
// Matrix representation (2D Array: rows x columns)
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
printf("Matrix elements:\n");
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
printf("%d ", matrix[r][c]);
}
printf("\n");
}
return 0;
}
3 Code Challenge
Challenge: Declare a single array containing 8 integers. Calculate the average of all the elements in the array. Print out the sum and the calculated average using formatted decimal outputs.