QUESTION 40 · Matrices and Dimensions
Explain how a two-dimensional array is passed to a function.
5 marksAnswer in brief
A two-dimensional array argument normally supplies a pointer to its first row. The function must use the correct row type and valid active dimensions.
Fixed-width interface
void show(int a[][3], int rows);
/* equivalent parameter type: int (*a)[3] */
Meaning
The actual array has rows containing three ints. In the parameter, the outer array form adjusts to a pointer to one such row. The first bound may be omitted because the function receives a pointer, but the row width 3 describes the row type and the step used by a[i]. It must match the caller’s actual object.
Example explanation
main holds a 2-by-3 matrix and calls show(a, 2). The function visits two rows and three columns. The example prints the same matrix without copying the whole object. Since its parameter is not const-qualified, the function could modify elements, although this show function only reads them.
Capacity and active dimensions
In the matrix calculation programs, actual arrays have MAX columns even when only some columns are active. Their parameters therefore also use MAX as the row width. Passing cols as a logical count does not change the actual row width. C also supports other suitable dimension-aware forms, but this unit uses fixed-width parameters for clarity.
Important points and complexity
Do not cast an incompatible matrix to int ** or use a wrong row width. Pass and validate the row count separately. A display function for r rows and a fixed c-column width takes O(rc) time and O(1) auxiliary space beyond the input array.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void show(int a[][3], int rows)
{
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < 3; ++j) {
if (j > 0) { putchar(' '); }
printf("%d", a[i][j]);
}
putchar('\n');
}
}
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
show(a, 2);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
1 2 3
4 5 6
Related exam questions
Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
- July 2021 · Q3(a) · 7 marks
Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.
Paper P04 · page 1 - September 2023 · Q1(d) · 1 marks
What is a two-dimensional array?
Paper P06 · page 1
View this category in the exam question bank →