繁体   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