4 min read•Last Updated on August 13, 2024
Multi-dimensional arrays in C let you store data in grid-like structures. They're super useful for representing tables, matrices, and other complex data. You can create, access, and manipulate these arrays easily, making them a powerful tool in your programming toolkit.
Understanding how multi-dimensional arrays work in memory is key. They're stored in contiguous memory locations, which affects how you access and work with them. This knowledge helps you write more efficient code and avoid common pitfalls when using these arrays.
data_type array_name[rows][columns]
data_type
specifies the type of elements stored in the array (int, float, char, etc.)array_name
is the identifier used to refer to the arrayrows
and columns
define the dimensions of the arrayint arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
int arr[3][4] = {{1, 2}, {5, 6}}
int arr[][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}}
malloc()
function
int **arr = (int **)malloc(rows * sizeof(int *));
malloc()
callsarr[i][j]
accesses the element at row i
and column j
i
) represents the row, and the second index (j
) represents the columnarr[0][0]
arr[0][0]
, and the last element is arr[2][3]
arr[1][2] = 10
assigns the value 10 to the element at row 1 and column 2for
loops
for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { // Access element at arr[i][j] } }
i
and j
) to access individual elements of the array
i
) represents the current rowj
) represents the current column within the rowi < rows
for the outer loop and j < columns
for the inner loopfor (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { printf("%d ", arr[i][j]); } printf("\n"); }
int max = arr[0][0]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } }
arr[0][0] arr[0][1] arr[0][2] arr[0][3] arr[1][0] arr[1][1] arr[1][2] arr[1][3] arr[2][0] arr[2][1] arr[2][2] arr[2][3]
arr[i][j]
using the formula:
&arr[i][j] = base_address + (i * num_columns + j) * sizeof(data_type)
base_address
is the memory address of the first element of the arraynum_columns
is the number of columns in the arraysizeof(data_type)
is the size of each element in bytesvoid function(int arr[][num_columns], int rows)