user2864293
user2864293

Reputation: 392

Accessing individual objects created by "new", through pointer arithmetic

I am dynamically creating 3 objects of MyClass.

MyClass *ptr = new MyClass[3];

I'm assuming ptr is the address of the first instance of said object. I can do

(*ptr).doStuff();

However, when I try to access the 2nd object, via

(* (ptr + sizeof(MyClass)) ).doStuff();

It throws an exception. How am I supposed to get at the other objects?

Upvotes: 2

Views: 58

Answers (4)

barak manos
barak manos

Reputation: 30136

Here are the options (from most recommended to least recommended):

ptr[1].doStuff();
(ptr+1)->doStuff();
(*(ptr+1)).doStuff();
((MyClass*)((char*)ptr+sizeof(MyClass)))->doStuff();
(*(MyClass*)((char*)ptr+sizeof(MyClass))).doStuff();

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

Pointer arithmetic already takes the size of the pointee type into account. So you should plus 1, not sizeof(MyClass).

Otherwise you are plussing too far.

Upvotes: 2

Geier
Geier

Reputation: 904

That's because incrementing ptr by 1 does not simply increment the pointer by 1 byte. Instead, it moves the pointer so far as to point to the next element to the array. Instead of your final line you have to write

(* (ptr + 1) ).doStuff();

or:

(ptr+1)->doStuff();

or, even more readable, as the commenters have suggested:

ptr[1]->doStuff();

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

The valid code will look as

(* (ptr + 1) ).doStuff();

This is so-called the pointer arithmetic. You "shift" the pointer to the number of elements you want.

Upvotes: 2

Related Questions