动态结构数组错误

Dynamic Struct Array Error

我在尝试创建 ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants];

时遇到错误 "Allocation of incomplete type"

这是我的代码:

#include <fstream>
#include <iostream>

using namespace std;

struct ContestantInfo;

int main()
{
    //opens all the files for input and output
    fstream contestantsFile("contestants.txt", ios::in);
    fstream answerKeyFile("answers.txt", ios::in);
    fstream reportFile("report.txt", ios::out);

    //used to determine how many contestants are in the file
    int numberOfContestants = 0;
    string temp;

    //checks to see if the files opened correctly
    if(contestantsFile.is_open() && answerKeyFile.is_open() && reportFile.is_open()){

        //counts the number of lines in contestants.txt
        while(getline(contestantsFile, temp, '\n')){

            numberOfContestants++;

        }

        //Puts the read point of the file back at the beginning
        contestantsFile.clear();
        contestantsFile.seekg(0, contestantsFile.beg);

        //dynamic array that holds all the contestants ids
        string *contestantIDNumbers = new string [numberOfContestants];

        //Reads from the contestants file and initilise the array
        for(int i = 0; i < numberOfContestants; i++){

            getline(contestantsFile, temp, ' ');

            *(contestantIDNumbers + i) = temp;

            //skips the read point to the next id
            contestantsFile.ignore(256, '\n');

        }

        ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants];

    }
    else
    {
        cout << "ERROR could not open file!" << endl;
        return 0;
    }

}

struct ContestantInfo{

    string ID;
    float score;
    char *contestantAnswers;
    int *questionsMissed;

};

Struct ContestantInfo 中的指针最终也应该指向动态数组,如果这有任何改变的话。我是一名学生所以如果我做了一些愚蠢的事情,请不要犹豫。

你有什么理由需要使用指针吗?

如果你使用 std 向量而不是使用 new 进行动态数组分配,这会让事情变得更简单。

在您的结构中,您可以使用整数向量和字符串向量而不是指向字符的指针。

您还可以有一个参赛者信息向量。

这样你就不用担心资源管理了,让标准模板库来搞定。

查看此处了解更多信息:

http://www.cplusplus.com/reference/vector/vector/

根据编译器,您的问题是结构的前向声明(当您尝试创建它们的数组时)。查看此问题及其答案:Forward declaration of struct

此致