Skip to study material
← Question index

QUESTION 18 · Pointers and Arrays

Explain pointers to rows of a two-dimensional array.

5 marks

Answer in brief

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.

Declaration

int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*p)[3] = a;

Row and element access

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.

Why the width matters

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.

Difference from int **

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.

Bounds and complexity

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.

C program and output

/* 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;
}

Sample input and output

This example uses values already written in the program.

Output

Selected = 6

Related exam questions

Related questions in the pointers arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • June 2022 · Q4(b) · 8 marks

    What is a pointer? Write a C program to sum array elements using a pointer.

    Paper P03 · page 1

View this category in the exam question bank →