将指针数组传递给函数

Passing pointer array to function

本文关键字:函数 指针 数组      更新时间:2023-10-16

我有以下情况。下面的程序虽然在我运行时编译得很好,但它停止了工作。有人能帮我找出问题吗?我想我在函数中使用了错误的指针,但我不知道如何修复它并使其在中工作

#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 filen";
    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            

使用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 filen";
        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 

使用malloc来分配非POD类型是UB,在您的案例中,由于没有调用std::string构造函数,因此book实例将在字符串中包含一些垃圾。它不仅仅是垃圾字符串,它很可能是指向一些随机位置的垃圾指针
如果确实需要手动分配内存,则应该使用std::vector或至少使用new,以便在堆中创建新的Book实例
如果你真的,真的必须使用malloc,你可以使用放置new在你以某种方式分配的原始内存中创建有效的std::string(在你的情况下是malloc)。

您需要使用

Book* bookInfo = new Book[100];

相反。这是因为,在C++中,struct是一个对象(就像class一样),对普通旧数据以外的任何对象调用malloc都是未定义的行为

记住使用delete[] bookInfo;来释放内存(注意方括号)。如果单独使用delete,则会出现更多未定义的行为。

还要确保你的阅读量不超过100行;否则您将溢出数组:还有更多未定义的行为

最后,考虑使用像std::vector这样的标准模板库容器。

关于:

Book bookInfo[100];

这完全避免了堆分配,应该可以达到您的目的。