如何创建指向结构的指针数组

时间:2013-05-03 15:55:44

标签: c++

我有这个

struct Book{
    string id;
    string title;
    string author;
};

然后我想动态创建一个指向struct的指针数组。我已经尝试了这个,我得到了分段错误。

Book *array[]= (Book*) malloc(sizeof(Book)); 

我想创建一个书籍列表(id,title,author)。我应该尝试创建一个结构数组吗?

1 个答案:

答案 0 :(得分:4)

<强>不..

改为std::vector<Book>


#include <string>
#include <vector>
#include <iostream>

struct Book {
    std::string id;
    std::string title;
    std::string author;
};

int main()
{
    Book b1 = { "0", "Title1", "Author1" };
    Book b2 = { "1", "Title2", "Author2" };

    std::vector<Book> books;
    books.push_back(b1);
    books.push_back(b2);

    std::cout << books.at(0).title << std::endl;
    // Expected output: "Title1"
}

Simple