我有以下情況。下面的程序雖然編譯得很好,但當我運行它時,它停止工作。任何人都可以幫我找到問題嗎?我想我使用了錯誤的指針到函數,但我不知道如何解決它,並使其工作將指針數組傳遞給函數
#include <fstream>
//some other includes
using namespace std;
struct Book{
string id;
string title;
string authorName;
string authorSurname;
};
int load(Book* booksInfo)
{
int count = 0;
ifstream fin;
fin.open("myfile.txt");
if (!fin.is_open())
{
cout << "Unable to open myfile.txt file\n";
exit(1);
}
while (fin.good())
{
getline(fin, booksInfo[count].id, '#');
getline(fin, booksInfo[count].title, '#');
getline(fin, booksInfo[count].authorName, '#');
getline(fin, booksInfo[count].authorSurname, '#');
count++;
} //end while
fin.close();
return 0;
} //end load()
//some other functions here
int main()
{
Book * bookInfo;
bookInfo = (Book*) malloc(sizeof(Book)*100);
//some code here
load(bookInfo);
//some code here
return 0;
} //end main
「停止工作」是什麼意思? –
在C++中,優先使用new(而不是malloc)(在某些情況下有必要)。你也可能想看看STL容器(最值得注意的是std :: vector) – Borgleader
爲什麼選擇malloc?不要使用malloc。使用新的。 –