簡體   English   中英

將指針數組傳遞給函數

[英]Passing pointer array to function

我有以下情況。 以下程序雖然在我運行時可以正常編譯,但是它停止工作。 誰能幫我找到問題嗎? 我認為我在函數中使用了錯誤的指針,但我不知道如何修復它並使它起作用

#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            

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

使用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 

您需要使用

Book* bookInfo = new Book[100];

代替。 這是因為,在C ++中, struct是一個對象(就像class ),並且對除普通舊數據以外的任何其他對象調用malloc都是未定義的行為

請記住使用delete[] bookInfo;釋放內存delete[] bookInfo; (請注意方括號)。 如果您自己使用delete ,那將是未定義的行為

另外,請確保閱讀的內容不超過100行; 否則您將溢出數組:還有更多未定義的行為

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

關於什么:

Book bookInfo[100];

這完全避免了堆分配,應該可以滿足您的目的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM