Skip to content

Multi-dimensional arrays in C

Multi-dimensional arrays in C are arrays that have more than one dimension, allowing you to represent data in multiple dimensions such as rows and columns. They are often used to represent matrices, tables, and other structured data.

Syntax:

In C, the syntax for declaring multi-dimensional arrays involves specifying the dimensions within square brackets.

datatype arrayName[size1][size2]…[sizeN];

Here, datatype specifies the type of elements in the array, arrayName is the name of the array, and size1, size2, …, sizeN specify the sizes of each dimension.

Initialization:

Multi-dimensional arrays can be initialized similarly to one-dimensional arrays, using nested curly braces to specify the elements.

datatype arrayName[size1][size2]…[sizeN] = {

    {val11, val12, …, val1N},

    {val21, val22, …, val2N},

    …,

    {valM1, valM2, …, valMN}

};

Accessing Elements:

To access elements of a multi-dimensional array, you use multiple indices separated by square brackets.

arrayName[index1][index2]…[indexN];

Example:

Here’s an example of a 2D array representing a 3×3 matrix:

#include <stdio.h>

int main() {

    int matrix[3][3] = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    // Accessing elements

    printf(“Element at row 2, column 3: %d\n”, matrix[1][2]);  // Outputs: 6

    return 0;

}
Passing Multi-dimensional Arrays to Functions:

When passing multi-dimensional arrays to functions, you need to specify the sizes of all dimensions except for the first one. This is because in C, arrays decay into pointers to their first elements when passed to functions.

void function(int array[][3]) {

    // Function code

}

Alternatively, you can pass a pointer to the array along with its dimensions as separate arguments.

void function(int (*array)[3], int rows) {

    // Function code

}

Limitations:

  • Multi-dimensional arrays can quickly become complex to manage, especially as the number of dimensions increases.
  • The size of each dimension must be known at compile time, making it difficult to work with dynamically-sized multi-dimensional arrays.
  • Memory layout for multi-dimensional arrays is contiguous, with elements of the last dimension stored next to each other. This can impact cache performance for large arrays with many dimensions.

Understanding multi-dimensional arrays is essential for working with structured data in C, especially for applications involving matrices, images, and other multi-dimensional data structures.