Background
Multidimensional arrays in C were originally designed for ease of use with tables and matrices. The classic two-dimensional array is an array of arrays, allowing simple syntax for working with elements of tabular data. Over time, the approach has evolved, especially when dealing with variable-length arrays.
The Problem
Incorrect declaration and initialization of multidimensional arrays lead to compilation errors or logical failures. When passing a multidimensional array to a function, many developers get confused due to specification requirements — all dimensions except the first must be explicitly specified.
The Solution
Declaring a two-dimensional array:
int matrix[3][4];
Full initialization:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
When passing to a function, all sizes except the first must be explicitly stated:
void printMatrix(int m[][3], int rows) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < 3; ++j) printf("%d ", m[i][j]); printf(" "); } }
With the introduction of the C99 standard, functions accepting variable-length arrays can be declared:
void foo(int rows, int cols, int a[rows][cols]);
Key Features:
1. Can a function be declared that accepts a two-dimensional array without specifying the second size?
No, C requires that all sizes except the first be known at compile time. This relates to pointer arithmetic when accessing elements.
Example of an error:
// Error: void process(int arr[][], int rows); // Not allowed
2. What happens if not all elements of a multidimensional array are initialized?
Remaining elements will automatically be filled with zeros if the array is static or global. For a local array with partial initialization, implicitly initialized elements will also be zeros.
int a[2][3] = {{1}, {4}}; // a[0][1] and a[0][2], a[1][1] and a[1][2] will become 0
3. What is the difference between an array of pointers and a two-dimensional array?
A two-dimensional array is a single memory block. An array of pointers is a set of pointers to separate (possibly separately allocated) one-dimensional arrays. This is important, for example, when allocating memory for "ragged" arrays.
Attempting to declare and pass a two-dimensional array to a function without specifying the second size, resulting in a compilation error. A surface-level fix by replacing it with a pointer leads to undefined or incorrect behavior during further calculations.
Pros:
Cons:
The developer explicitly states the sizes of all dimensions, clarifying in documentation the order of element storage in memory, thereby reducing the number of errors in further maintenance.
Pros:
Cons: