尝试创建指针数组,但是当我尝试定位时(运行时错误)

时间:2019-05-04 14:41:19

标签: c++ pointers

我尝试为新对象创建指针数组。 我的对象是团队。 在团队中,我有两个针对足球运动员的指针(Footballer **玩家)。 现在,我尝试创建为团队添加玩家的方法(所有方法都与动态内存配合使用)。 创建方法后,该方法可以工作,但是我有一个错误。 在这一行: “((* help)[i] =(* Players)[i];” 当我加入2支队伍的比赛时,它的实力就会下降。第一个玩家输入好,但是当我去寻找下一个玩家时,我就选择了错误的位置。 我认为我的分配有误。 感谢您的帮助,我试图弄清楚,但是很难,如果有不清楚的地方我会尝试解释

#include "Team.h"

void Team::addPlayer(Footballer *newPlayer)
{
    AmountOfPlayers++;
    Footballer **help;
    help = new Footballer*[AmountOfPlayers - 1];
    for (int i = 0; i < AmountOfPlayers - 1; i++)
    {
        help[i] = new Footballer;
        (*help)[i] = (*Players)[i];                // this line call for operator "=" of footballer and i have worng location...
    }
    for (int i = 0; i < AmountOfPlayers - 1; i++)
    {
        delete Players[i];
    }
    delete[] Players;
    Players = new Footballer*[AmountOfPlayers];
    for (int i = 0; i < AmountOfPlayers; i++)
    {
        if (i == AmountOfPlayers - 1)
        {
            Players[i] = new Footballer;
            (*Players)[i] = *newPlayer;
        }
        else
        {
            Players[i] = new Footballer;
            (*Players)[i] = (*help)[i];
        }
    }
}

0 个答案:

没有答案