C-Style Arrays

2D C-Style Arrays

How do I create and work with 2D C-style arrays in C++?

Abstract art representing computer programming

2D C-style arrays in C++ are essentially arrays of arrays. Each element in a 2D array is itself a 1D array.

Here's how you can create and work with 2D C-style arrays:

Declaration and Initialization

The following example demonstrates how we can create a 2D C-style array, and optionally provide it with initial values:

// Declare a 3x3 int array
int arr[3][3];

// Initialize with values
int arr[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Accessing Elements

Here, we show how to access and modify elements in a 2D C-style array:

// Access individual elements
// Accessing row 1, column 2
int val = arr[1][2];

// Modify an element
// Modifying row 0, column 0
arr[0][0] = 10;

Passing to Functions

We can pass a 2D C-style array to a function in the usual way:

#include <iostream>

void print2DArray(int arr[][3], int rows) {
  for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < 3; ++j) {
      std::cout << arr[i][j] << ' ';
    }
    std::cout << '\n';
  }
}

int main() {
  int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
  print2DArray(arr, 2);
}
1 2 3
4 5 6

Note that when passing a 2D array to a function, you must specify all dimensions except the first one.

Flattening

2D arrays are laid out contiguously in memory, so you can also treat them as a 1D array:

int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

// Treat as 1D array
for (int i = 0; i < 6; ++i) {
    std::cout << *(*arr + i) << ' ';
}

However, for more complex and dynamic 2D arrays, consider using a std::vector<std::vector<int>> instead. It offers more flexibility and convenience at the cost of some performance overhead.

Understanding how to work with 2D C-style arrays is important for certain applications and for understanding how arrays are laid out in memory, but in modern C++, 2D std::vectors or other library containers are often preferred for their safety and ease of use.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved