簡體   English   中英

動態結構數組錯誤

[英]Dynamic Struct Array Error

當我嘗試創建ContestantInfo *contestantStructArray = new ContestantInfo [numberOfContestants];時,出現錯誤“分配不完整的類型” 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內部的指針最終也應指向動態數組。 我是學生,所以如果我做一些愚蠢的事情,請不要退縮。

根據編譯器,您的問題是該結構的正向聲明(在嘗試創建它們的數組時)。 請參閱此問題及其答案: 結構的正向聲明

問候

您有任何理由需要使用指針嗎?

如果您使用std向量代替帶new的動態數組分配,這將使您的事情變得更簡單。

在您的結構中,如果有整數,則可以有一個向量,還有一個字符串的向量,而不是指向char的指針。

您可能還會有參賽者信息向量。

然后,您無需擔心資源管理,可以讓標准模板庫來處理它。

請參閱此處以獲取更多信息:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM