声明struct表时出现Std::bad_alloc错误

std::bad_alloc error when declaring struct table

本文关键字:bad alloc 错误 Std struct 声明      更新时间:2023-10-16

我声明了简单的结构:

struct Heap {
  int size;
  int *heap_array;
};

当我试图创建表,其中k是int从stdin:

Heap *rooms = new Heap[k];
我:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

从字面上看,使用int是可以的:

Heap *rooms = new Heap[0];

如何声明这样的表?

stdin读取的值可能无效。如果读取失败,您可以在其中设置一些默认值,例如2^32。