0
0
CHow-ToBeginner · 3 min read

How to Declare 2D Array in C: Syntax and Examples

In C, you declare a 2D array using the syntax type name[rows][columns]; where type is the data type, and rows and columns are the sizes of the array. For example, int matrix[3][4]; declares a 2D array with 3 rows and 4 columns.
📐

Syntax

The general syntax to declare a 2D array in C is:

  • type: The data type of the elements (e.g., int, float).
  • name: The name of the array variable.
  • rows: Number of rows in the array.
  • columns: Number of columns in the array.

This creates a grid-like structure where you can store data in rows and columns.

c
type name[rows][columns];
💻

Example

This example declares a 2D array of integers with 3 rows and 4 columns, assigns values, and prints them.

c
#include <stdio.h>

int main() {
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

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

Common Pitfalls

Common mistakes when declaring 2D arrays in C include:

  • Forgetting to specify both dimensions (rows and columns).
  • Mixing up rows and columns order when accessing elements.
  • Using variable sizes without constants or macros (not allowed in standard C).

Always specify both sizes except when initializing immediately, where the first dimension can be omitted.

c
#include <stdio.h>

int main() {
    // Wrong: missing second dimension
    // int matrix[3][]; // This will cause a compile error

    // Correct:
    int matrix[3][4];

    // Accessing elements correctly:
    matrix[0][1] = 10; // row 0, column 1

    return 0;
}
📊

Quick Reference

ConceptDescriptionExample
DeclarationDefine a 2D array with fixed rows and columnsint arr[2][3];
InitializationAssign values at declarationint arr[2][3] = {{1,2,3},{4,5,6}};
Access ElementUse row and column indicesarr[0][2] = 10;
LoopingUse nested loops to traversefor(i=0;i<2;i++) for(j=0;j<3;j++)
Partial SizeFirst dimension can be omitted if initializedint arr[][3] = {{1,2,3},{4,5,6}};

Key Takeaways

Declare a 2D array with type name[rows][columns]; specifying both dimensions.
Use nested loops to access or modify elements in row-column order.
Always specify the second dimension; the first can be omitted only during initialization.
Common errors include missing dimensions and mixing row/column indices.
Initialize arrays at declaration for easier and safer usage.