【问题标题】:Dynamic Struct Array Error动态结构数组错误
【发布时间】:2017-10-06 07:01:20
【问题描述】:

我在尝试创建 ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants]; 时收到错误“分配不完整类型”

这是我的代码:

#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 中的指针最终也应该指向动态数组,如果这有任何改变的话。我是一名学生,所以如果我做了一些愚蠢的事情,请不要退缩。

【问题讨论】:

    标签: c++ arrays struct dynamic-arrays


    【解决方案1】:

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

    问候

    【讨论】:

    • 好吧,我大致了解那个帖子。您能否建议包含可以解决此问题的代码,或者创建这样的动态结构数组不起作用?
    • @FinnWilliams 当然,您只需将结构定义放在 main 之前。
    【解决方案2】:

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

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

    在您的结构中,您可以有一个向量 if int 和一个字符串向量,而不是指向 char 的指针。

    您还可以拥有参赛者信息的向量。

    然后您无需担心资源管理,可以让标准模板库处理它。

    查看这里了解更多信息:

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

    【讨论】:

    • 是的,分配限制我们只能使用动态数组。
    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2020-12-30
    相关资源
    最近更新 更多