RawrBawr
RawrBawr

Reputation: 23

Accessing a structure array through a pointer

I have a class with a structure for its position:

class thing
{
    void setCoOrds(int, int, int);

    string name;
    struct location
    {
        int x;
        int y;
        int z;
    } coOrd;
};

Then in a function I created an array of type thing.

int main()
{
    thing * p_myThings = new thing[5];
    // call array element here to use setCoOrds()
    delete p_myThings;

    return 0; 
}

From the main function how would I access, lets say, thing element [3] so that I can use its .setCoOrds() function?

Upvotes: 0

Views: 63

Answers (4)

Kajgies
Kajgies

Reputation: 31

You should use:

p_myThings[3].setCoOrds(x, y, z);

And for deleting pointer arrays you should use delete[] not delete

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

I suppose that member function

void setCoOrds(int, int, int);

has public access control. In this case you can use the following constructions

p_myThings[3].setCoOrds( x, y, z );

or

( *( p_myThings + 3 ) ).setCoOrds( x, y, z );

or

( p_myThings + 3 )->setCoOrds( x, y, z );

Upvotes: 0

Sumeet
Sumeet

Reputation: 779

It should be:

p_myThings[3].setCoOrds

Also the

setCoOrds

is private by default which will not allow you to call the function.

Upvotes: 1

Drax
Drax

Reputation: 13288

int main()
{
    thing * p_myThings = new thing[5];

    p_myThings[3].setCoOrds(42,21,0);

    delete[] p_myThings; // use delete[] for arrays btw

    return 0; 
}

Upvotes: 0

Related Questions