Aneesh Narayanan
Aneesh Narayanan

Reputation: 3434

Access object array using pointer

This is my sample program

#include "stdafx.h"

class B
{
public:
    int i,j;
};

class A
{
public:
    B b[2];
    A()
    {
        b[0].i = 1;
        b[0].j = 2;
        b[1].i = 3;
        b[1].j = 4;
    }
    B* function()
    {
        return b;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    B* obj = new B();
    obj = a.function();
    return 0;
}

I have to get the array of b objects(ie, need all the values, b[0].i, b[0].j,b[1].i and b[1].j)

But when I tried it with this code, only one object is returned.

Upvotes: 0

Views: 1815

Answers (3)

mfontanini
mfontanini

Reputation: 21900

Yes, you are actually returning the a pointer to the array b[2]. What you want to do now is to iterate through the items in that pointer. You can print them by adding this lines to you code:

A a;
B *obj = a.function();
std::cout << obj[0].i << ", " << obj[0].j << "; " << obj[1].i << ", " << obj[1].j << std::endl;

And of course, including iostream at the beginning of your file:

#include <iostream>

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612784

What you state in the question is not true. Two objects are indeed returned. Access them with obj[0] and obj[1].

I guess you are looking at obj under the debugger and the IDE cannot know that you mean for your pointer obj to be an array of two objects. So the tooltips will only show the first object, obj[0], or *obj. But the other object, obj[1] is definitely there.

Add the following line after the call to a.function:

printf("%d, %d, %d, %d\n", obj[0].i, obj[0].j, obj[1].i, obj[1].j);

and you will see this output:

1, 2, 3, 4

Note that there is no point in the line B* obj = new B(); since you immediately overwrite obj. You should do it this way:

B* obj = a.function();

Your code is also a little dangerous in that you must keep a alive at least as long as you are making references to obj.

Upvotes: 1

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

This code

B* function()
        {
          return b;
        }

returns the pointer to the first element of array

B b[2];

which can be dereferenced applying pointer arithmetics and/or operator [].

Upvotes: 1

Related Questions