v010dya
v010dya

Reputation: 5848

How to loop through a multidimenional array through pointers in C++

Looping through a simple array is no problem, but what is the correct way to loop through the multidimentional array by using pointers?

#include <iostream>

int main(int argc, char* argv[])
{
    int data1[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for(auto *p = data1; p!=data1+9; ++p)
    {
        std::cout << (*p) << ' ';
    }
    std::cout << std::endl;


    int data2[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    for(auto *lineP = data2; lineP!=data2+3; ++lineP)
    {
        for(auto *p = &(lineP[0]); p!= &(lineP[3]); ++p)
        {
            std::cout << (*p) << ' ';
        }
        std::cout << std::endl;
    }
}

In here data1 is looped through correctly producing the expected output. But data2 loop is wrong in some way, because the output is not the values of the elements, but rather the addresses.

Example output:

1 2 3 4 5 6 7 8 9 
0x7ffde45b77a0 0x7ffde45b77ac 0x7ffde45b77b8 
0x7ffde45b77ac 0x7ffde45b77b8 0x7ffde45b77c4 
0x7ffde45b77b8 0x7ffde45b77c4 0x7ffde45b77d0 

Upvotes: 0

Views: 49

Answers (2)

DynasticSponge
DynasticSponge

Reputation: 1441

Given: int mdArray[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

  • mdArray is a pointer to a 3 element array
  • each element in that array is a pointer to a 3 element array
  • each element in those arrays is an integer

So just nest your original syntax inside itself substituting the de-referenced var instead of the name of the multidimensional array itself

    int mdArray[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    
    for(auto *d1 = mdArray; d1 != (mdArray + 3); d1++)
    {
      for(auto *d2 = *(d1); d2 != (*(d1) + 3); d2++)
      {
        std::cout << *(d2) << ' ';
      }
      std::cout << std::endl;    
    }

Upvotes: 2

user8776755
user8776755

Reputation: 70

for(auto *p = &(lineP[0]); p!= &(lineP[3]); ++p) { std::cout << (*p) << ' '; }

Should be

for(auto p = &(lineP[0]); p!= &(lineP[3]); ++p) { std::cout << (*p) << ' '; }

Be aware of auto p. You asked a pointer of an adress. You made à pointer pointer. Then dereference it, the result is adress, not value.

You could also cout **p

Upvotes: 1

Related Questions