KMN
KMN

Reputation: 159

Accessing an element in a vector of struct c++ using pointers

Hi I'm new to c++ and wanted to ask a questions on how to access an element of struct inside a vector using pointers. lets say I have a struct:

struct pets{    //struct of pets
string name;
int age;
}

int main() {
pets a = {bolt, 2};
pets b = {crash, 3};

vector<pets> x;
x.push_back(a);
x.push_back(b);
vector<person> *ptr = &x;
???

} 

using the pointer ptr to the vector x how would I be able to access the first the age of the the first element stored in my vector of pets? I am aware its easier to use

x[0].age

but I wanted to acces the elements member using a pointer to a vector of struct. Can anyone help?

Upvotes: 1

Views: 78

Answers (1)

Oblivion
Oblivion

Reputation: 7374

You need to dereference it first:

ptr[0][0].age;
// ^^^ make sure you don't use >0 for the first one

or

(*ptr)[0].age;

Live on Godbolt.

Upvotes: 1

Related Questions