QUESTION 17 · Pointers and Arrays
What pointer type matches the first row of int a[2][3]?
2 marksAnswer
int (*)[3], a pointer to an array of three int.
- Declare it as int (*p)[3] = a;.
- It is not the same type as int **.
QUESTION 17 · Pointers and Arrays
int (*)[3], a pointer to an array of three int.
QUESTION 18 · Pointers and Arrays
A two-dimensional array is an array of row arrays. Its usual conversion produces a pointer to its first row, not a pointer to pointer.
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*p)[3] = a;p identifies the first row. p + 1 identifies the next row because its pointed-to type is an array of three ints. p[1][2] reads 6. The equivalent form *(*(p + 1) + 2) first selects the second row and then its third element.
The compiler needs the row width to calculate the correct step between rows. A function parameter int a[][3] adjusts to this pointer-to-row type. Passing a logical column count does not change an actual object declared with a different fixed row width.
An int ** identifies an int * object. A rectangular int a[2][3] instead contains ints grouped into row arrays; it does not contain an intermediate array of int * values. Casting between these layouts does not rearrange the storage and does not justify incompatible access.
Both row and column indices must be valid. a[0][3] is not a permitted replacement for a[1][0]. Reading a fixed valid element takes O(1) work. Traversing all r × c elements takes O(rc) time and O(1) auxiliary space beyond the matrix. The example reads one element and displays its value.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*p)[3] = a;
printf("Selected = %d\n", *(*(p + 1) + 2));
return 0;
}This example uses values already written in the program.
Selected = 6Related questions in the pointers arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
What is a pointer? Write a C program to sum array elements using a pointer.
Paper P03 · page 1