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?
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.
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 *.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With