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
| Concept | Description | Example |
|---|---|---|
| Declaration | Define a 2D array with fixed rows and columns | int arr[2][3]; |
| Initialization | Assign values at declaration | int arr[2][3] = {{1,2,3},{4,5,6}}; |
| Access Element | Use row and column indices | arr[0][2] = 10; |
| Looping | Use nested loops to traverse | for(i=0;i<2;i++) for(j=0;j<3;j++) |
| Partial Size | First dimension can be omitted if initialized | int 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.