Christoph90
Christoph90

Reputation: 673

Access multidimensional array elements with a pointer in C++

I'm 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'm expecting *pia to be the second array in ia and therefore the output to be 4567.

However the output is 4814197056, so I'm obviously doing it wrong. How do I the access the elements in the rows correctly?

Upvotes: 3

Views: 206

Answers (3)

vmcloud
vmcloud

Reputation: 652

I used the below way to print, It works well.

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

In precedence table of C++, [] has higher priority than *.

Upvotes: 1

Wintermute
Wintermute

Reputation: 44023

As it stands, you would have to write

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

because [] 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;

Addendum: The reason you get the output you do, by the way, is that *pia[i] is another way of writing pia[i][0]. Since pia[0] is ia[1], pia[1] is ia[2], and pia[2] and beyond are garbage (because ia is too short for that), you print ia[1][0], ia[2][0] and then garbage twice.

Upvotes: 5

Exceptyon
Exceptyon

Reputation: 1582

  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;

Upvotes: 0

Related Questions