</>
CompilerOnline
Open Interactive Editor

C Arrays & Memory Layout

Arrays in C

An array is a collection of items of the same type stored at contiguous memory locations. The size of a C array is fixed at compile-time, and elements are accessed using zero-based indexing.

Array Decay:

In most expressions, the name of an array decays into a pointer pointing to its first element. For instance, referencing the array scores is equivalent to writing &scores[0].

C does not perform array boundary checks. Accessing an index beyond the array's declared size results in undefined behavior, potentially corrupting other memory variables or crashing the program.

Multi-dimensional arrays are represented as arrays of arrays, laid out in row-major order in memory. Strings in C are represented as contiguous character arrays terminated by a null character (\0).

Two-Dimensional Matrices

Two-dimensional arrays represent tables with rows and columns. They are declared with two sets of square brackets and indexed via row and column indicators.

c
#include <stdio.h>
int main() {
    int matrix[2][2] = {{1, 2}, {3, 4}};
    printf("Element 1,1: %d\n", matrix[1][1]);
    return 0;
}
c
#include <stdio.h>

int main() {
    int scores[3] = {85, 92, 78};
    for (int i = 0; i < 3; i++) {
        printf("Score %d: %d\n", i, scores[i]);
    }
    return 0;
}