0
0
CppHow-ToBeginner · 3 min read

How to Create 2D Array in C++: Syntax and Examples

In C++, you create a 2D array by specifying the type, followed by the array name and two sizes inside square brackets, like int arr[3][4];. This creates a grid with 3 rows and 4 columns where you can store values. You can then access elements using two indices, for example, arr[0][1].
📐

Syntax

A 2D array in C++ is declared by specifying the data type, the array name, and two sizes inside square brackets. The first size is the number of rows, and the second is the number of columns.

  • Type: The kind of data stored (e.g., int, double).
  • Name: The variable name for the array.
  • Rows: Number of rows in the array.
  • Columns: Number of columns in the array.
cpp
int arr[3][4];
💻

Example

This example creates a 3x4 integer 2D array, assigns values to each element, and prints the array in a grid format.

cpp
#include <iostream>

int main() {
    int arr[3][4];

    // Assign values
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            arr[i][j] = i * 4 + j + 1; // Fill with numbers 1 to 12
        }
    }

    // Print values
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            std::cout << arr[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12
⚠️

Common Pitfalls

Common mistakes when working with 2D arrays in C++ include:

  • Forgetting to specify both dimensions when declaring the array.
  • Accessing indices out of bounds, which causes undefined behavior.
  • Mixing up row and column indices when accessing elements.
  • Trying to assign values to the entire array at once without loops.

Always use loops to assign or access elements safely.

cpp
/* Wrong: Missing second dimension */
// int arr[3]; // This is a 1D array, not 2D

/* Correct: Specify both dimensions */
int arr[3][4];

/* Wrong: Accessing out of bounds */
// arr[3][0] = 10; // Index 3 is invalid for rows 0-2

/* Correct: Access within bounds */
arr[2][3] = 10;
📊

Quick Reference

ConceptDescriptionExample
DeclarationCreate a 2D array with fixed rows and columnsint arr[3][4];
Access ElementUse row and column indices starting at 0arr[0][1] = 5;
LoopingUse nested loops to traverse rows and columnsfor(int i=0;i<3;i++) for(int j=0;j<4;j++) arr[i][j]=0;
Out of BoundsAvoid accessing indices outside declared sizesValid: arr[2][3], Invalid: arr[3][0]

Key Takeaways

Declare 2D arrays with two sizes: rows and columns inside square brackets.
Access elements using two indices: row first, then column.
Use nested loops to assign or read values safely.
Avoid out-of-bound indices to prevent errors.
2D arrays store data in a grid-like structure for easy organization.