Accessing multidimensional array elements with a pointer in C ++

I am trying to access the elements of a multidimensional array with a pointer in C ++:

#include<iostream>

int main() {

  int ia[3][4] = {
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11}
  };

  int (*pia)[4] = &ia[1];
  std::cout << *pia[0] 
    << *pia[1]
    << *pia[2]
    << *pia[3]
    << std::endl;

  return 0;
}

      

I expect to *pia

be the second array in ia

and so the output will be 4567.

However the output is 4814197056, so I am obviously doing it wrong. How do I correctly access items in strings?

+3


source to share


3 answers


As it stands, you will have to write

std::cout << (*pia)[0] ...

      

because it []

binds more strongly than *

. However, I think what you really want to do is



int *pia = ia[1];
std::cout << pia[0] 
          << pia[1]
          << pia[2]
          << pia[3]
          << std::endl;

      

Appendix: The reason you get the conclusion that you are drawing by the way is because *pia[i]

- this is another way of writing pia[i][0]

. Since pia[0]

- ia[1]

, pia[1]

- ia[2]

, pia[2]

and above is garbage (because it's ia

too short for that), you print ia[1][0]

, ia[2][0]

and then twice is garbage.

+5


source


I used the following printing method, it works well.

std::cout << (*pia)[0]
         << (*pia)[1]
         << (*pia)[2]
         << (*pia)[3] 
         << std::endl;

      



In the C ++ priority table, [] has a higher priority than *.

+1


source


  int *pia[] = { &ia[1][0], &ia[1][1], &ia[1][2], &ia[1][3] };

      

or

    int* pia = static_cast<int*>(&ia[1][0]);
  std::cout << pia[0] << " "
    << pia[1] << " "
    << pia[2] << " "
    << pia[3] << " "
    << std::endl;

      

0


source







All Articles