C Language
6. Arrays & StringsBeginner10 min read

Arrays in C: 1D, 2D & Memory Arrangement

Store collections of homogeneous data in contiguous memory. Learn 1D and 2D arrays, matrix operations, and passing arrays to functions.

Key Takeaways & Core Concepts
  • An array is a fixed-size collection of items of the same data type stored contiguously in memory.
  • Array indexing is 0-based: an array of size N has indices from 0 to N-1.
  • The array name decays into a pointer to its first element in most expressions.
  • C does NOT perform array bounds checking: accessing out-of-bounds indices causes undefined behaviour.
  • 2D arrays are stored in memory in Row-Major order.

1D Array Declaration & Memory Layout

When you declare int arr[5];, C allocates 5 consecutive integer slots in memory. If an int is 4 bytes, the entire array occupies 20 continuous bytes.

C Code Example
1int numbers[5] = {10, 20, 30, 40, 50};
2printf("%d", numbers[0]); // First element: 10
3printf("%d", numbers[4]); // Last element: 50
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
3 lines
No Automatic Bounds Checking

If you access `numbers[10]` on an array of size 5, C will not throw an 'IndexOutOfBoundsException'. It will read whatever garbage bytes happen to be at that memory offset or cause a segmentation fault.

2D Arrays & Passing Arrays to Functions

A 2D array represents data in rows and columns, such as matrices or coordinate grids. In memory, C lays out elements row after row (Row-Major format).

2D Matrix Arithmetic and Passing Arrays
1#include <stdio.h>
2
3#define ROWS 2
4#define COLS 3
5
6// When passing 2D arrays, all dimension bounds except the first must be specified
7void printMatrix(int matrix[ROWS][COLS]) {
8 for (int r = 0; r < ROWS; r++) {
9 for (int c = 0; c < COLS; c++) {
10 printf("%3d ", matrix[r][c]);
11 }
12 printf("\n");
13 }
14}
15
16int main(void) {
17 int matA[ROWS][COLS] = {
18 {1, 2, 3},
19 {4, 5, 6}
20 };
21
22 printf("2D Matrix Elements:\n");
23 printMatrix(matA);
24
25 // Demonstrate contiguous memory
26 printf("\nMemory addresses of row 0 elements:\n");
27 for (int c = 0; c < COLS; c++) {
28 printf("matA[0][%d] at %p\n", c, (void*)&matA[0][c]);
29 }
30
31 return 0;
32}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
32 lines
Note: Notice each element address increments by exactly 4 bytes (sizeof(int)), proving contiguous memory.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

If int arr[5] is stored starting at memory address 1000, and sizeof(int) is 4 bytes, what is the address of arr[3]?

Intermediate