0
#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 *)(&friends)'从'FriendInfo *'转换为'FriendInfo'。怎么了?

4

1 回答 1

1

你不能friends像那样重新分配,因为它不是一个指针,它是一个数组。即使可以,您所做的也不安全,因为GrowArray只是在堆栈上创建了一个新数组,该数组将在函数返回时被销毁。

您应该使用newanddelete创建和销毁数组(然后您可以将它们作为指针传递),或者最好使用std::vectorwhich 为您处理所有这些东西。

于 2013-07-11T20:32:43.503 回答