Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pointers to iterate through multidimensional array

If you can use pointers to iterate through an array like this:

for (int *iter = arr; iter != std::end(arr); ++iter) {
    // code
}

How do you iterate through a multidimensional array with pointers (without using auto)?

EDIT: I am assuming this is an int[][] such as {{3, 6, 8}, {2, 9, 3}, {4, 8, 2}}

like image 628
LazySloth13 Avatar asked Mar 22 '23 09:03

LazySloth13


2 Answers

If you declared array as arr[][], and yes you can because they are stored sequentially in memory. You can do:

for(int * iter = &arr[0][0]; iter != &arr[0][0] + col * row; iter++)
//...
like image 52
SwiftMango Avatar answered Apr 21 '23 00:04

SwiftMango


How about trying like this:-

const int* d = data;
for ( int i = 0; i < width; ++i )
    for ( int j = 0; j < height; ++j )
        for ( int k = 0; k < depth; ++k )
            sum += *d++;

Check this tutorial

like image 20
Rahul Tripathi Avatar answered Apr 21 '23 02:04

Rahul Tripathi