Skip to main content

Pointers in pass by reference; 2D array

Short answer

Passing by reference in C uses pointers: pass the address of a variable, and the function dereferences it to modify the original. For a 2D array, a pointer to an array of columns (e.g., int (*p)[3]) can access elements as *(*(p+i)+j), or a flat pointer with row-major offset.

What is the role of pointers in passing parameters to functions by reference? Give example, how 2 dimensional array can be accessed by a pointer.

Role of pointers in passing parameters by reference

C passes arguments by value, so a function normally changes only copies. If the address of a variable is passed to a function whose parameter is a pointer, the function can reach the original variable with * and change it. This is how call by reference is done in C. It also allows a function to return more than one value, and it avoids copying large arrays or structures (an array name is already an address).

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
...
swap(&x, &y);       /* x and y are really exchanged */

Accessing a 2D array by a pointer

A 2D array is stored row by row. With int m[2][3]:

  • m points to row 0; m + i points to row i.
  • *(m + i) is row i (an array of 3 ints) and *(*(m + i) + j) is the element m[i][j].
  • With a pointer to a row, int (*p)[3] = m;, the same expression *(*(p + i) + j) works.
  • Or use a flat pointer int *q = &m[0][0]; where element [i][j] is *(q + i*3 + j).
#include <stdio.h>

void swap(int *a, int *b)       /* pass by reference */
{
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void)
{
    int x = 4, y = 9;
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int (*p)[3] = m;                 /* pointer to an array of 3 ints */

    swap(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++)
            printf("%d ", *(*(p + i) + j));      /* same as m[i][j] */
        printf("\n");
    }
    int *q = &m[0][0];               /* flat access */
    printf("m[1][2] = %d = *(q+5) = %d\n", m[1][2], *(q + 5));
    return 0;
}

Output:

After swap: x = 9, y = 4
1 2 3 
4 5 6 
m[1][2] = 6 = *(q+5) = 6

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →