Two-Dimensional Arrays in C
C supports multi-dimensional arrays through a straightforward declaration syntax:
type arrayName[size1][size2];
A three-dimensional integer array with dimensions 5×10×4 would be declared as:
int cuboid[5][10][4];
The most common multi-dimensional array is the two-dimensional array, which can be visualized as a table with rows and columns. To declare an array with x rows and y columns:
type arrayName[x][y];
For example, a table with 3 rows and 4 columns:
int matrix[3][4];
Each element is accessed using the notation matrix[i][j], where i represents the row index and j represents the column index.
Initializing Two-Dimensional Arrays
Arrays can be initialized by specifying values for each row within curly braces:
int data[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
The nested braces are optional. The equivalent single-line initialization:
int data[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Accessing Array Elements
Element are accessed using row and column indices. The following retrieves the element at row 2, column 3:
int value = data[2][3];
Practical Example
The following program demonstrates array enitialization and element access using nested loops:
#include <stdio.h>
int main(void)
{
int values[5][2] = {
{0, 0},
{1, 2},
{2, 4},
{3, 6},
{4, 8}
};
int row, col;
for (row = 0; row < 5; row++)
{
for (col = 0; col < 2; col++)
{
printf("values[%d][%d] = %d\n", row, col, values[row][col]);
}
}
return 0;
}
Output:
values[0][0] = 0
values[0][1] = 0
values[1][0] = 1
values[1][1] = 2
values[2][0] = 2
values[2][1] = 4
values[3][0] = 3
values[3][1] = 6
values[4][0] = 4
values[4][1] = 8
While C supports arrays of any dimension, one-dimensional and two-dimensional arrays are the most frequently used in practice.
Passing Arrays to Functions
When passing an array to a function, the parameter can be declared in three equivalent ways. Each approach informs the compiler that it will receive a pointer to an integer.
Parameter as a Pointer
void processArray(int *arr)
{
/* function body */
}
Parameter as a Sized Array
void processArray(int arr[10])
{
/* function body */
}
Parameter as an Unsized Array
void processArray(int arr[])
{
/* function body */
}
Complete Example
The following function calculates the average of array elements:
#include <stdio.h>
double calculateAverage(int numbers[], int length);
int main(void)
{
int scores[] = {1000, 2, 3, 17, 50};
double result;
result = calculateAverage(scores, 5);
printf("Average: %.2f\n", result);
return 0;
}
double calculateAverage(int numbers[], int length)
{
int index;
double avg;
double total = 0.0;
for (index = 0; index < length; index++)
{
total += numbers[index];
}
avg = total / length;
return avg;
}
Output:
Average: 214.40
Note that the array dimension is irrelevant within the function, as C does not perform bounds checking on array parameters.