函数采用一个充满结构的数组,并返回一个具有相同结构的更大数组
Function taking an array filled with structures, and returning a bigger array with the same structures
#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 与朋友和日子一起获取初始数组,创建另一个带有额外位置的数组,并将原始数组复制到新数组中。但是当我使用该功能时,我收到此错误 ->错误:无法将"(FriendInfo*((和朋友("从"FriendInfo*"转换为"FriendInfo"。怎么了?
你不能
像这样重新分配friends
,因为它不是一个指针,它是一个数组。即使你可以,你正在做的事情也是不安全的,因为GrowArray
只是在堆栈上创建一个新数组,当函数返回时,该数组将被销毁。
您应该使用 new
和 delete
来创建和销毁数组(然后您可以将它们作为指针传递(,或者最好使用 std::vector
为您处理所有这些内容。