Multidimensional Arrays
2D array rows aur columns mein data store karta hai — grid, matrix, ya table jaisa. Declare karte waqt dono dimensions batane padte hain: int grid[3][4] matlab 3 rows, 4 columns.
Memory mein 2D array actually ek single continuous block hota hai (row-major order — pehli row pura, phir dusri row) — [row][col] sirf ek convenient tarika hai us memory ko access karne ka.
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", grid[i][j]);
}
}
// 1 2 3 4 5 6- 2D array = rows × columns, grid jaisa
- Memory mein actually ek continuous block (row-major)
- grid[row][col] se access karo
C mein 2D se aage bhi ja sakte ho — 3D array (int cube[2][3][4]) ya aur zyada dimensions bhi possible hain, lekin practical use rare hai (2D sabse common hai, jaise matrices, grids, tables).
int cube[2][2][2] = {
{{1,2},{3,4}},
{{5,6},{7,8}}
};
printf("%d\n", cube[1][0][1]); // 62D array function mein pass karte waqt pehla dimension (rows) chhod sakte ho, lekin column count zaroor batana padta hai — compiler ko pata hona chahiye har row kitni badi hai, taaki memory ko sahi se navigate kar sake.
void printGrid(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
}
}