這是為我的一個課程分配的,我被卡住了,我必須使用這些必需的結構,它們是:
struct Pokemon {
int dex_num;
string name;
string type;
int num_moves;
string* moves;
};
struct Pokedex {
string trainer;
int num_pokemon;
Pokemon* dex;
};
我的任務是使用 .txt 檔案中的可用資訊創建一組口袋妖怪。我將 Pokedex 結構命名為“Pokedex 資料”;我堅持的是擦除所述陣列
void delete_info(Pokedex &);
這個文本上面的功能是我必須如何洗掉它,我很困惑我試過了
delete []data.dex;
data.dex = NULL;
我試圖取消參考它并且我已經嘗試過
delete []dex;
delete []data;
等等
每一個都讓我陷入了段錯誤,或者只是一般的錯誤和宣告問題。
編輯這是我應該如何分配記憶體
Pokemon * dex = create_pokemons(7);
這就是我主要要求的
Pokemon* create_pokemons(int y) {
Pokemon* dex = new Pokemon[y];
return dex;
}
我不太確定出了什么問題。
編輯我不允許使用向量
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Pokemon {
int dex_num;
string name;
string type;
int num_moves;
string* moves;
};
struct Pokedex {
string trainer;
int num_pokemon;
Pokemon* dex;
};
string getName(string&);
Pokemon* create_pokemons(int);
void populate_pokedex_data(Pokedex & , ifstream &);
string* create_moves(int);
void populate_pokemon(Pokemon &, ifstream &);
void delete_info(Pokedex &);
int main () {
Pokedex data;
int y;
ifstream myFile;
Pokemon * dex = create_pokemons(6);
populate_pokedex_data(data , myFile);
delete_info(data);
if(myFile.is_open()) {
myFile.close();
}
}
Pokemon* create_pokemons(int y) {
Pokemon* dex = new Pokemon[y];
return dex;
}
string getName(string &str) {
cout << "What is your name trainer" << endl;
cin >> str;
cout << str << " is your name, thats pretty cringe" << endl;
return str;
}
void populate_pokedex_data(Pokedex &data, ifstream &myFile) {
string str;
myFile.open("pokedex.txt",ios::in);
myFile >> data.num_pokemon;
data.trainer = str;
for (int i =0; i < data.num_pokemon; i ) {
populate_pokemon(data.dex[i], myFile);
}
}
void populate_pokemon(Pokemon &dex, ifstream &myFile) {
string str;
myFile >> dex.dex_num;
myFile >> dex.name;
myFile >> dex.type;
myFile >> dex.num_moves;
getline(myFile, str);
cout << dex.dex_num <<" ";
cout << dex.name << " ";
cout << dex.type << " ";
cout << dex.num_moves << endl;
}
void delete_info(Pokedex &data) {
delete [] data.dex;
data.dex = NULL;
}
uj5u.com熱心網友回復:
您的實施delete_info()是正確的。真正的問題是您main()正在創建一個Pokemon物件陣列,但從未將該陣列指標分配給該Pokedex::dex欄位,甚至根本沒有初始化該Pokedex::dex欄位。因此,當您的代碼嘗試使用該欄位訪問該陣列的內容或釋放該陣列時,它具有未定義的行為。Pokedex::dex
在main()中,您需要更改:
Pokemon * dex = create_pokemons(6);
為此:
data.dex = create_pokemons(6);
populate_pokedex_data()然后,在確定的值之后,該陳述句實際上應該移到內部data.num_pokemon,例如:
void populate_pokedex_data(Pokedex &data, ifstream &myFile) {
string str;
myFile.open("pokedex.txt",ios::in);
myFile >> data.num_pokemon;
data.trainer = str; // <-- you didn't read a value into str first!
data.dex = create_pokemons(data.num_pokemon); // <-- moved here!
for (int i =0; i < data.num_pokemon; i ) {
populate_pokemon(data.dex[i], myFile);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521004.html
標籤:C c 11视觉-C
