c++ - 将指针数组传递给函数

标签 c++

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

#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            

最佳答案

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

关于c++ - 将指针数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17491761/

相关文章:

c++ - 程序退出期间的函数局部静态初始化

c++ - Visual Studio 2015 "non-standard syntax; use ' &' to create pointer for member"

C++ 模板、静态方法和构造函数

c++ - 构造函数和对象创建中的“this”

c++ - 奇怪的 C++ 成员函数声明语法 : && qualifier

c++ - 为什么我的 CPP 在程序结束后随机运行

c++ - 如何去除图像中的小平行线?

c++ - C 从竖线字符分隔的文件中读入

c++ - 如果不是手动完成,子类是否会继承父类的析构函数?

c++ - 如何用一个信号量同步 3 个进程?