#include <iostream>
#include <string>
using namespace std;
struct FriendInfo
{
string name;
int last_day;
};
FriendInfo GrowArray(FriendInfo friend_list,int sizing);
int main()
{
int initial_friends;
cout << "How many friends would you like to add--> ";
cin >> initial_friends;
FriendInfo friends[initial_friends];
for (int i = 0; i < initial_friends;i++)
{
cout << "What is your friend's name?--> ";
cin >> friends[i].name;
cout << "When was the last time you talked to " << friends[i].name << " ?--> ";
cin >> friends[i].last_day;
}
for (int i = 0; i < initial_friends;i++)
cout << friends[i].name << " " << friends[i].last_day << "\n";
cout << "What would you like to do now?\n1. Add another friend?\n2. Update one of yourfriends?\n3. Sort friends by day?4. Quit.\n--> ";
int option;
cin >> option;
while (option != 4)
{
if (option == 1)
{
friends = GrowArray(friends,initial_friends);
cout << "What is your new friend's name?--> ";
cin >> friends[initial_friends].name;
cout << "When was the last time you talked to " << friends[initial_friends].name << " ?--> ";
cin >> friends[initial_friends].last_day;
}
}
}
FriendInfo GrowArray(FriendInfo friend_list, int sizing)
{
FriendInfo new_list[sizing + 1];
for (int i = 0;i < sizing;i++)
{
new_list[i].name = friend_list[i].name;
new_list[i].last_day = friend_list.last_day;
}
return new_list;
}
这个程序将结构放入一个包含朋友姓名的数组,以及他们与他们交谈的最后一天。稍后的选项之一是添加另一个朋友。函数GrowArray使用朋友和日期获取初始数组,使另一个数组生成额外的点并将原始数组复制到新数组中。但是,当我使用该功能时,我收到此错误 - &gt;错误:无法将'(FriendInfo *)(&amp; friends)'从'FriendInfo *'转换为'FriendInfo'。怎么了?
答案 0 :(得分:1)
你不能像那样重新分配friends
,因为它不是指针,它是一个数组。
即使你可以,你所做的事情也不安全,因为GrowArray
只是在堆栈上创建一个新的数组,当函数返回时它将被销毁。
您应该使用new
和delete
来创建和销毁数组(然后您可以将它们作为指针传递),或者最好使用处理所有这些东西的std::vector
对你而言。