-1

For one dimensional array, I have no problem accessing array element. For example --

#include<typeinfo>
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
int main()
{
        int a[3] = {1, 2, 3};
        cout << *(a + 0);
        return 0;
}

But when I am trying for 2 dimensional array, I am getting output of the kind --

#include<typeinfo>
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
int main()
{
        int a[][3] = {1, 2, 3};
        cout << *(a + 2);
        return 0;
}

Output --

0x7ffca0f7ebcc

How can I get output as 2(I will get 2 either by row major or column major order, but c++ follows row major array representation) in the format described in 1st example?

Ujjal Kumar Das
  • 191
  • 3
  • 15
  • That's because `*(a + 2)` for the second case yields a `int(*)[3]` result, so you get a pointer printed. Now how would you get the object from the pointer? (Also what's up with the irrelevant includes and usings...) – DeiDei Jul 28 '17 at 15:36

2 Answers2

1

This will give you the third element of the first row.

#include <iostream>    
int main()
{
    int a[][3] = {1, 2, 3};
    std::cout << *(*a + 2);
}

Although you might find a[0][2] easier to understand.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

For raw arrays, C++ inherits the rule from C that

a[i]

is transformed to

*(a + i);

To access a two-dimensional array, we can apply this rule twice:

a[i][j] => *(a[i] + j) => *(*(a + i) + j)

Although obviously the a[i][j] syntax is a lot easier to understand.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82