Data Structures 1D Arrays
2D Arrays Memory Layout

C++ Arrays: Complete Guide to 1D and 2D Arrays

Master C++ arrays with comprehensive examples of 1D arrays, 2D arrays, operations, memory representation, and practical applications. Learn efficient array manipulation techniques.

1D Arrays

Linear data structures

2D Arrays

Matrix/tabular data

Memory Layout

Contiguous storage

Operations

Traversal, search, sort

C++ Tutorial · Arrays

Arrays store fixed-size sequences. Learn C-style arrays, multidimensional layout, common pitfalls, and when to prefer std::array or std::vector in modern code.

C++ arrays infographic: 1D and 2D array declaration syntax, contiguous memory layout, initialization with braces, for-loop traversal, and 1D vs 2D comparison table
C++ arrays visual guide — one-dimensional arrays (linear index, contiguous memory) and two-dimensional arrays (row/column matrix, row-major layout) with declaration, initialization, access, and traversal examples for beginners and interview prep.

What you will learn

  • Declare and initialize one- and two-dimensional arrays
  • Traverse arrays with loops and range-based for
  • Understand row-major memory layout for 2D arrays
  • Avoid out-of-bounds access and undefined behavior
  • Compare raw arrays with std::array benefits

Why this topic matters

Arrays underpin algorithms, dynamic programming, and buffer handling. Interview questions often test indexing and memory layout.

Key terms & indexing

C++ arrays 2D array C++ std::array C++ array initialization

Understanding Arrays in C++

Arrays are fundamental data structures in C++ that store a fixed-size sequential collection of elements of the same type. They provide efficient access to elements using indices and are stored in contiguous memory locations.

1D Array Linear Structure

Single row of elements accessed by a single index. Perfect for lists and sequences.

2D Array Tabular Structure

Rows and columns matrix accessed by two indices. Ideal for grids and tables.

Contiguous Memory

Elements stored sequentially in memory for fast access via pointer arithmetic.

Fixed Size

Size must be known at compile time (unless using dynamic arrays).

Key Concepts:
  • Fixed Size: Array size cannot change after declaration
  • Homogeneous: All elements must be same data type
  • Zero-based Indexing: First element is at index 0
  • Contiguous Memory: Elements stored consecutively
  • Random Access: Direct access to any element via index

1. One-Dimensional (1D) Arrays

// Declaration syntax:
data_type array_name[size];

// Examples:
int numbers[5]; // Declare array of 5 integers
float prices[10]; // Declare array of 10 floats
char name[20]; // Declare array of 20 characters

Declaration and Initialization

Examples

1. Declare then assign
int nums[5];
nums[0] = 10; nums[1] = 20;
2. Full init list
int primes[] = {2,3,5,7,11};
3. Partial init
int sc[10] = {95, 88, 76}; // rest 0
4. All zeros
int zeros[10] = {0};
5. Loop init squares
int sq[5];
for (int i = 0; i < 5; i++)
    sq[i] = (i+1)*(i+1);
6. char string
char name[] = "John";

Memory Visualization

Memory Layout of int arr[5] = {10, 20, 30, 40, 50}
arr[0]
10
arr[1]
20
arr[2]
30
arr[3]
40
arr[4]
50

Contiguous memory addresses: &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]

Common Operations on 1D Arrays

Examples

1. Find max
int max = arr[0];
for (int i = 1; i < SIZE; i++)
    if (arr[i] > max) max = arr[i];
2. Sum elements
int sum = 0;
for (int i = 0; i < SIZE; i++) sum += arr[i];
3. Linear search
for (int i = 0; i < SIZE; i++)
    if (arr[i] == target) { pos = i; break; }
4. Reverse print
for (int i = SIZE-1; i >= 0; i--)
    cout << arr[i];
5. std::sort
sort(arr, arr + SIZE);
6. Count even/odd
if (arr[i] % 2 == 0) even++;
else odd++;

2. Two-Dimensional (2D) Arrays

// Declaration syntax:
data_type array_name[rows][columns];

// Examples:
int matrix[3][4]; // 3 rows, 4 columns matrix
float temperatures[7][24]; // 7 days, 24 hours
char tictactoe[3][3]; // 3x3 Tic-Tac-Toe board

Declaration and Initialization

Examples

1. 2x3 matrix
int m[2][3] = {{1,2,3},{4,5,6}};
2. Flat init
int m[2][3] = {1,2,3,4,5,6};
3. Partial rows
int m[3][3] = {{1,2},{4,5,6},{7}};
4. All zeros
int z[4][4] = {0};
5. Times table fill
int t[10][10];
for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
        t[i][j] = (i+1)*(j+1);
6. Array of strings
char names[][20] = {"Alice","Bob"};

Memory Visualization of 2D Arrays

Memory Layout of int arr[3][4]
[0][0]
arr[0][0]
[0][1]
arr[0][1]
[0][2]
arr[0][2]
[0][3]
arr[0][3]
[1][0]
arr[1][0]
[1][1]
arr[1][1]
[1][2]
arr[1][2]
[1][3]
arr[1][3]
[2][0]
arr[2][0]
[2][1]
arr[2][1]
[2][2]
arr[2][2]
[2][3]
arr[2][3]

Row-major order: Elements stored row by row in contiguous memory

Common Operations on 2D Arrays

Examples

1. Matrix add
C[i][j] = A[i][j] + B[i][j];
2. Transpose
cout << A[j][i];  // swap indices
3. Row sum
for (int j = 0; j < COLS; j++)
    rowSum += A[i][j];
4. Main diagonal
cout << A[i][i];
5. 2D search
if (A[i][j] == target)
    foundRow = i, foundCol = j;
6. Find min/max
if (A[i][j] > max) max = A[i][j];

3. Practical Applications

Student Marks Management System

Examples

1. Parallel arrays
string names[MAX];
int marks[MAX][5];
2. Average marks
float avg = (float)total / MAX_SUBJECTS;
3. Grade from avg
if (avg >= 90) grade = 'A';
else if (avg >= 80) grade = 'B';
4. Class average
classAvg += averages[i];
classAvg /= numStudents;
5. Top student
if (averages[i] > averages[top])
    top = i;
6. Validate marks
while (marks[i][j] < 0 || marks[i][j] > 100)
    cin >> marks[i][j];

Tic-Tac-Toe Game

Examples

1. Init board
char board[3][3];
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
        board[i][j] = ' ';
2. Place move
board[row][col] = currentPlayer;
3. Check row win
if (board[i][0]==p && board[i][1]==p && board[i][2]==p)
    return true;
4. Check diagonal
if (board[0][0]==p && board[1][1]==p && board[2][2]==p)
    return true;
5. Board full
if (board[i][j] == ' ') return false;
6. Switch player
currentPlayer = (currentPlayer=='X') ? 'O' : 'X';

4. Memory Management & Advanced Concepts

Array Pointers and Memory Addresses

Examples

1. arr == &arr[0]
int arr[5] = {10,20,30,40,50};
cout << arr;      // address
cout << &arr[0];  // same
2. Pointer arithmetic
int *p = arr;
cout << *(p + 2);  // arr[2]
3. sizeof array
int n = sizeof(arr)/sizeof(arr[0]);
4. Element address
cout << &arr[i];
5. 2D contiguous
int m[2][3] = {{1,2,3},{4,5,6}};
cout << &m[0][1];
6. Row-major layout
// m[i][j] stored row by row

Passing Arrays to Functions

Examples

1. Print 1D array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        cout << arr[i];
}
2. Modify array
void doubleArray(int arr[], int size) {
    for (int i = 0; i < size; i++) arr[i] *= 2;
}
3. Array sum
int arraySum(int arr[], int size) {
    int s = 0;
    for (int i = 0; i < size; i++) s += arr[i];
    return s;
}
4. 2D parameter
void printMatrix(int m[][3], int rows);
5. Pass by reference
// arrays always passed by reference
6. Get size at call
int size = sizeof(nums)/sizeof(nums[0]);
printArray(nums, size);

5. Best Practices & Common Errors

Common Error Example Solution
Array Index Out of Bounds int arr[5]; arr[5] = 10; Always check indices: 0 to size-1
Forgetting Array Size int arr[]; (no size specified) Specify size or initialize with values
Uninitialized Array int arr[10]; (contains garbage) Always initialize: int arr[10] = {0};
Wrong Loop Bounds for(i=1; i<=size; i++) Use: for(i=0; i
Passing Wrong Size to Functions void func(int arr[]) {...} Always pass size parameter: void func(int arr[], int size)
Assuming Arrays are Passed by Value Modifying array in function affects original Arrays are always passed by reference
Best Practices
  • Always initialize arrays when declaring them
  • Use const for array sizes that shouldn't change
  • Check array bounds before accessing elements
  • Use meaningful variable names for array indices
  • Prefer range-based for loops when possible (C++11)
  • Consider using std::array (C++11) for fixed-size arrays
  • Use std::vector for dynamic arrays
Performance Tips
  • Access array elements sequentially for better cache performance
  • Minimize array copying - pass by reference when possible
  • Use local arrays for small, frequently accessed data
  • Consider memory layout when designing algorithms
  • Avoid multidimensional arrays with varying row lengths

Summary & Key Takeaways

1D Arrays Summary
  • Linear collection of same-type elements
  • Fixed size, contiguous memory
  • Zero-based indexing (0 to n-1)
  • Efficient random access O(1)
  • Use for lists, sequences, vectors
2D Arrays Summary
  • Matrix/table structure (rows × columns)
  • Row-major memory layout
  • Double indexing: [row][column]
  • Use for matrices, grids, tables
  • Common in image processing, games

When to Use Arrays

  • Use arrays when: Size is fixed and known at compile time, need random access, working with multidimensional data
  • Consider alternatives when: Size is dynamic (use std::vector), need advanced operations (use std::array in C++11)
  • Remember: Arrays are fundamental building blocks for more complex data structures

Next Steps

Mastering arrays is crucial for advancing in C++ programming. Practice with array-based algorithms, explore dynamic arrays with pointers, and learn about Standard Template Library (STL) containers like vector, array, and valarray for more advanced use cases.

Frequently asked questions

What happens if I access a[10] on a 5-element array?

Undefined behavior—may crash or corrupt memory. Always stay within bounds.

Are arrays the same as pointers?

Array names often decay to pointers; sizeof(array) differs from sizeof(pointer)—covered in the pointers lesson.

Should I use std::array or C arrays?

Prefer std::array when size is known at compile time—it knows its length and works with STL algorithms.