I am new to C++ arrays and pointer and came across a few problems. I have some inquiries for the following code I wrote.
Version 1:
int main()
{
string a, b;
int age;
Dog d[5];
Dog *p = new Dog[5];
for (int i = 0; i < 5; i++)
{
d[i].setwe(3 * i);
d[i].setag(i);
p[i] = Dog(d[i]);
}
p[5]->showCnt();
//^^^^^^^^^^^^^^ Error above
for (int j = 0; j < 5; j++)
{
delete [] p;
}
return 0;
}
Version 2:
int main()
{
string a, b;
int age;
Dog d[5];
Dog *p[5];
for (int i = 0; i < 5; i++)
{
d[i].setwe(3 * i);
d[i].setag(i);
//p[i] = Dog(d[i]);
p[i] = &d[i];
}
p[5]->showCnt();
return 0;
}
From what I understand I might have written wrongly in version 1 but I want to understand why p is not seen as a pointer in version 1?
This is the hint I got from error: base operand of '->' has non pointer-type 'Dog' .
I am also unsure which is a better way(version 1 or version 2) to copy an object array to a pointer object array. I would like to apologise in advanced if I have understood it wrongly. Thank you.
p[5]->showCnt()
is ilegal because your array of objects has only 5 positions, starting by 0 and ending on 4. So, you just have to replace p[5]->showCnt()
by p[4]->showCnt()
.
About the better version to use, use version 2 if you want to work with static sizes and use version 1 if you want to manage p
dynamically to work with more than 5 objects at some moment of your program runtime. Short answer: version 1 is better!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.