-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?

1
  • 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...) Commented Jul 28, 2017 at 15:36

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.