[英]Dynamically allocate an array of structs with C++
我正在嘗試動態分配記錄數組。 當我使用./a.out運行程序時,它似乎可以正常工作,但是當我嘗試運行程序從.txt文件(./myProg <)輸入數據時,它將重復記錄整個數組中的第一行文本並崩潰,最后沒有打印出所選擇的書。 我的猜測是我沒有正確創建數組,但似乎無法弄清楚我的問題是什么。
struct Book {
char *title; //entered with no spaces
int date; // in the form ddmmyy
};
Book *createRecord(int);
void input(Book *, int);
void display(Book *, int, int);
void destroyRecord(Book *);
int main() {
int arrN = 0;
int n = 0;
cout << "Enter size of array: ";
cin >> arrN;
Book *bookArr;
bookArr = new Book[arrN];
bookArr = createRecord(arrN);
input(bookArr, arrN);
cin.ignore();
cout << "Book: ";
cin >> n;
display(bookArr, arrN, n);
destroyRecord(bookArr);
return EXIT_SUCCESS;
}
Book *createRecord(int arrN){
struct Book *bookArr;
bookArr = new Book[arrN];
return bookArr;
}
void input(Book *bookArr, int arrN) {
for(int i = 0; i < arrN; i++){
char arrFirst[20];
cin.ignore();
cout << "Name: ";
cin.getline(arrFirst, 20);
strcpy((bookArr[i]).title = new char, arrFirst);
cout << "Score: ";
cin >> (bookArr[i]).date;
}
}
void display(Book *bookArr, int arrN, int n) {
if (0 <= n && n <= arrN){
cout << (bookArr[n-1]).title << " " << (bookArr[n-1]).date << endl;
}
}
void destroyRecord(Book *bookArr) {
delete [] (bookArr)->title;
delete bookArr;
}
好吧,首先,您要分配兩個數組:
bookArr = new Book[arrN]; // <-- leaked
bookArr = createRecord(arrN);
那是內存泄漏。
其次:
(bookArr[i]).title = new char
那就是分配一個單個字符,您試圖將整個字符串復制到其中。 那應該是:
// two lines please!
bookArr[i].title = new char[20];
strcpy(bookArr[i].title, arrFirst);
第三:
if (0 <= n && n <= arrN){
邊界檢查不正確。 上限應為n < arrN
,然后為索引n
。 通過索引n - 1
,您可以打印-1st索引。
最后但並非最不重要的一點是:
struct Book {
std::string title;
int date;
}
std::vector<Book> bookArr;
問題1:
修復顯示功能中的數組索引問題:
void display(Book *bookArr, int arrN, int n) {
if (0 <= n && n <= arrN){
cout << (bookArr[n - 1]).title << " " << (bookArr[n - 1]).date << endl;
}
}
至
void display(Book *bookArr, int arrN, int n) {
if (0 < n && n <= arrN){
cout << (bookArr[n - 1]).title << " " << (bookArr[n - 1]).date << endl;
}
}
當n = 0
, bookArr[-1]
在您的代碼中bookArr[-1]
錯誤。
問題2:
將字符數組而不是單個字符分配給行標題,更改:
strcpy((bookArr[i]).title = new char, arrFirst);
至
strcpy((bookArr[i]).title = new char[20], arrFirst);
不確定輸入問題,但是您絕對不會按需創建數組。 在您的代碼中,您將創建一個書本數組,然后在createRecord函數中分配一個新的書本數組,並用它替換原始的書本數組。 與您期望發生的事情不同,您最終得到了一組未初始化的Book指針。
這就是你應該做的...
// Allocate an array of books
Book *bookArr;
bookArr = new Book[arrN];
// Preallocate the records
for ( int iBook = 0; iBool < arrN; iBook++ )
{
bookArr[ iBook ] = createRecord();
}
...
Book *createRecord()
{
// Allocate one new book
struct Book *pbook = new book;
return pbook;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.