如何无限制地重新分配结构数组

How to realloc an array of structs without a limit

基本上,我有一个动态分配的结构数组。

  using namespace std;
  struct library
  {
    string bookname;
    string author;
    int bookno;
  };
  int main()
  {
           library *lib=NULL;
           lib=malloc(sizeof(lib)*1);
           lib=(library*)realloc(lib,2);
           cout<<"Enter Book Name: "<<endl;
           getline(cin,lib[i]->bookname);
 }

在上面的程序中,我为库创建了一个结构数组。我已经从 1 space 重新分配到 2 spaces,可以增加到更多。但是我在获取每个数组成员的成员变量的输入时遇到问题。 lib[i] 在这里导致错误。

您的 struct librarystd::string 个成员,因此 "POD"(普通旧数据)class 也不是。这意味着简单的 C 内存分配不会起作用,因为不会调用字符串构造函数和析构函数。

做您想做的最简单的方法就是使用 std::vector<library>。这将 运行 正确构造函数和析构函数,并自动调整自身大小。如果需要,您可以使用 reserve()shrink_to_fit().

手动控制 vector 的分配大小

如果您真的、真的必须使用 malloc() 和朋友,那么您将需要使用放置 new 和手动析构函数调用。像下面这样的东西可能会起作用:

library *lib = nullptr;
lib = static_cast<library*>(malloc(sizeof(library)*2)); // note not sizeof(lib)
lib = new (lib) library[2]{}; // default construct an array of library at the given location
cout<<"Enter Book Name: "<<endl;
getline(cin,lib[0].bookname);
// ...do other library stuff...
lib[0].~library(); // destroy librarys
lib[1].~library();
free(lib); // deallocate storage

但请注意,您仍然无法使用 realloc()。您必须创建一个新数组,调用 copy/move 放置新的构造函数,然后销毁并删除原始数组。

或者只使用 std::vector,它会为您完成这一切。

仅从代码来看,有几处错误

  1. 你说你的问题来自:lib[i] 嗯,提供的代码片段从未声明 [​​=11=]
  2. lib 是一个指针,当您将 [] 与指针一起使用时,您正在引用它,这意味着 -> 将不起作用,而只需使用 . ,如下所示: lib[i].bookname
  3. Tristan Brindle 是正确的,您需要使用 new