2013-07-05 207 views
0

我有以下情況。下面的程序雖然編譯得很好,但當我運行它時,它停止工作。任何人都可以幫我找到問題嗎?我想我使用了錯誤的指針到函數,但我不知道如何解決它,並使其工作將指針數組傳遞給函數

#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    
+3

「停止工作」是什麼意思? –

+3

在C++中,優先使用new(而不是malloc)(在某些情況下有必要)。你也可能想看看STL容器(最值得注意的是std :: vector) – Borgleader

+1

爲什麼選擇malloc?不要使用malloc。使用新的。 –

回答

3

這是UB使用malloc分配非POD類型,你的情況的書實例會在字符串中包含一些垃圾,因爲沒有調用構造函數std::string。它不會只是垃圾字符串,它很可能是指向一些隨機位置的垃圾指針。
如果您確實需要手動分配內存以在堆中創建新的Book實例,則應該使用std::vector或至少new
如果你真的,真的必須使用malloc,你可以使用展示位置new在原始內存中創建有效的std::string s你已經以某種方式分配了(在你的情況下通過malloc)。

+0

如果他們必須'malloc',他們可以使用[Placement New](https://en.wikipedia.org/wiki/Placement_syntax)來初始化 – Mgetz

+0

@Mgetz我敢打賭,事實並非如此,而是增加了一個註釋。 – alexrider

1

您需要使用

Book* bookInfo = new Book[100]; 

代替。這是因爲在C++中,struct是一個對象(就像class),並且在除之外的任何東西上調用malloc未定義的行爲

請記住使用delete[] bookInfo;(請注意方括號)釋放你的記憶。如果您自己使用delete,那就多一點未定義的行爲

另外請確保您不要讀取超過100行;否則你會溢出數組:更多未定義的行爲

最後,考慮使用標準模板庫容器,如std::vector

+0

thanx您的觀點!我想知道,如果我使用「新」而不是malloc什麼可以使用,而不是realloc? – Panagiotis

+1

@Panagiotis,技術上安置新的,但認真,使用一個載體。 – chris

3

使用std::vector存儲書籍清單:

#include <fstream> 
#include <vector> 
//some other includes 
using namespace std; 

struct Book{ 
    string id; 
    string title; 
    string authorName; 
    string authorSurname; 
    }; 

vector<Book> load() 
{ 
    ifstream fin; 
    Book book; 
    vector<Book> books; 
    fin.open("myfile.txt"); 

    if (!fin.is_open()) 
    { 
     cout << "Unable to open myfile.txt file\n"; 
     return books; 
    } 

    while (fin.good()) 
    { 
     getline(fin, book.id, '#'); 
     getline(fin, book.title, '#'); 
     getline(fin, book.authorName, '#'); 
     getline(fin, book.authorSurname, '#'); 
     books.push_back(book); 
    } //end while 

    fin.close(); 

    return books; 
} //end load() 

//some other functions here 

int main() 
{ 
    vector<Book> books = load(); 
    return 0; 
} //end main 
0

什麼:

Book bookInfo[100]; 

這完全避免了堆分配,應該成爲你的目的。

+0

沒有,這不會做,我需要動態綁定和釋放內存 – Panagiotis