如何为成员类型为字符串的结构变量分配内存

How to allocate memory for a struct variable whose members are of type string

我的结构:

struct Company {
    string name;
    string profit_tax;
    string address;
};

我使用以下行分配:

Company* a = (Company*)calloc(m, sizeof(Company));

long long m =pow(10,9)+9 但是指针 a 在分配后是一个空指针。我不知道为什么会这样?请告诉我解决方案,谢谢!

您为计算机分配了太多内存(除非您有大量内存)。

参见 this godbolt example,计算表明在他们的硬件上您将尝试分配 96GB 内存!

如果这是一个练习,也许你在必须分配的大小上有错字? 如果没有,您可以尝试将 std::string 替换为 indexes/pointers 到存储字符串的位置。它应该可以节省一些内存,但是您仍然会遇到问题。否则,您将不得不以不同的方式处理数据,即分块处理。

如果您使用的是 C++,为什么要使用 calloc?您可以简单地使用 std::vector<company> companies(m); ,这将分配内存并构造所有对象。不易出错,可读性更高。