3

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?

3
  • Try this int * pia = ia[1]; Commented Nov 28, 2014 at 10:29
  • 1
    No warnings with ´-std=c++11 -Wall -Wextra -pedantic´. @i486: ´error: invalid type argument of unary ‘*’ (have ‘int’) std::cout << *pia[0]´ Commented Nov 28, 2014 at 10:38
  • ... std::cout << pia[0]; Commented Nov 28, 2014 at 10:58

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I wasn't aware that the index operator can be used on pointers that way. So in the original code (with (*pia)[i]) I used a mixture of a pointer to int[] and array indexing whereas your suggestion relies on pointers alone (and row-major order). Are there any advantages in using "plain" pointer arithmetic here or is it a matter of style?
It looks clearer and more common. And anyway it is exactly the same as array indexing. This is because arrays decay into pointers at the drop of a hat; whenever you write arr[i], the array decays into a pointer on which pointer arithmetic then proceeds to happen.
1

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 *.

Comments

0
  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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.