What is Multidimensional Array in C: Explanation and Example
multidimensional array in C is an array of arrays, allowing storage of data in a table-like structure with rows and columns. It is declared by specifying multiple sizes in square brackets, such as int arr[3][4] for a 2D array with 3 rows and 4 columns.How It Works
Think of a multidimensional array like a grid or a spreadsheet where data is organized in rows and columns. Instead of just a single line of boxes (like a simple array), you have multiple lines stacked together. Each position in this grid can hold a value, and you access it by specifying both the row and the column.
In C, a multidimensional array is actually an array where each element is itself an array. For example, a 2D array with 3 rows and 4 columns means you have 3 arrays, each containing 4 elements. This helps organize data that naturally fits into tables, like a chessboard or a calendar.
Example
This example shows how to declare, initialize, and print a 2D array in C.
#include <stdio.h> int main() { int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; }
When to Use
Use multidimensional arrays when you need to store data in a structured form like tables, grids, or matrices. They are useful in applications such as image processing (pixels in rows and columns), game boards (like tic-tac-toe or chess), and mathematical computations involving matrices.
They help keep related data organized and make it easier to access elements using two or more indices, which represent different dimensions.
Key Points
- A multidimensional array is an array of arrays, allowing multiple indices to access elements.
- Commonly used as 2D arrays (rows and columns), but can have more dimensions.
- Declared by specifying sizes for each dimension, e.g.,
int arr[3][4]. - Useful for representing tables, grids, and matrices in programs.