Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating 2D array with pointer expressions in C

Tags:

c

pointers

I'm practicing pointers and want to substitute pointer operations in place of the arrays to traverse through the elements of the array. I have read numerous articles and cannot grasp this concept. Can someone explain?

Here I made a 2D array and iterated through it using a basic nested for-loop, but want to use pointers;

int test[3][2] = {1,4,2,5,2,8};

for (int i = 0 ; i < 3; i++) {

    for (int j = 0; j < 2; j++) {

        printf("%d\n", test[i][j]);
    }
}
like image 851
ryan Avatar asked Dec 11 '22 03:12

ryan


2 Answers

int test[3][2] = {{1,4},{2,5},{2,8}};

// Define a pointer to walk the rows of the 2D array.
int (*p1)[2] = test;

// Define a pointer to walk the columns of each row of the 2D array.
int *p2 = NULL;

// There are three rows in the 2D array.
// p1 has been initialized to point to the first row of the 2D array.
// Make sure the iteration stops after the third row of the 2D array.
for (; p1 != test+3; ++p1) {

    // Iterate over each column of the arrays.
    // p2 is initialized to *p1, which points to the first column.
    // Iteration must stop after two columns. Hence, the breaking
    // condition of the loop is when p2 == *p1+2
    for (p2 = *p1; p2 != *p1+2; ++p2 ) {
        printf("%d\n", *p2);
    }
}
like image 200
R Sahu Avatar answered Dec 30 '22 12:12

R Sahu


In some compilers you can also use a single loop, treating a multidimensional array as a one-dimensional array read in row-major order.

This is mentioned in King's C Programming: A Modern Approach (2nd ed., p268).

#include <stdio.h>

int main(void)
{
    int test[3][2] = {{1,4},{2,5},{2,8}}, *p;

    for(p = &test[0][0]; p <= &test[2][1]; p++)
    {
        printf("%d\n", *p);
    }
    return 0;
}
like image 43
p-robot Avatar answered Dec 30 '22 12:12

p-robot