【发布时间】:2015-02-06 04:06:00
【问题描述】:
我正在尝试动态分配记录数组。当我使用 ./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;
}
【问题讨论】:
标签: c++ arrays dynamic-memory-allocation records