我正在尝试通过指针访问该结构。我认为问题出在第13行。谁能告诉我问题出在哪里以及如何解决?
#include <iostream>
struct friends {
std::string name;
std::string lastName;
int age{};
};
int main() {
using namespace std;
int numberOfFriends{0};
cout << "Please enter the number of the friends: ";
cin >> numberOfFriends;
friends *dost[numberOfFriends];
for (int i = 0; i < numberOfFriends; ++i) {
cout << "Please enter the name of " << i + 1 << " friend: ";
cin>>(dost[i]->name);
cout << "Please enter the last name of " << i + 1 << " friend: ";
cin >> dost[i]->lastName;
cout << "Please enter the age of " << i + 1 << " friend: ";
cin >> dost[i]->age;
}
cout << "You entered following data. Please have a look: " << endl;
cout << "****************************************************" << endl;
for (int j = 0; j < numberOfFriends; ++j) {
cout << "Friend :" << j + 1 << endl;
cout << "Name :" << dost[j]->name << endl;
cout << "Last Name :" << dost[j]->name << endl;
cout << "Full Name :" << dost[j]->name << " " << dost[j]->lastName << endl;
cout << "Age :" << dost[j]->age << endl;
cout << "****************************************************" << endl;
}
}
答案 0 :(得分:4)
问题确实出在
friends *dost[numberOfFriends];
您不为指针分配任何内存,并且可变长度数组也不是可移植的。
替换是
std::vector<friends> dost(numberOfFriends);
尽管您将倾向于使用dost[i]->
,但是您将需要用dost[i].
替换dost.at(i).
,因为这会在索引上进行运行时边界检查。