【问题标题】:User defined type used in dynamic allocated 2d array动态分配的二维数组中使用的用户定义类型
【发布时间】:2021-12-11 14:14:58
【问题描述】:

假设我们有一个简单的结构

struct S {
     int a;
     int b;
     int c;
}

现在我们要创建一个指针数组(二维数组 5x5):

S** arr = new S*[5];
for (int i = 0; i < 5; ++i)
    arr[i] = new S[5];

我的问题是:

  1. 使用new 为该数组动态分配内存是否正确?我们不应该在某个地方使用sizeof(S) 吗?
  2. 如果使用malloc 而不是new,代码会是什么样子?下面的代码是否正确?
S** arr = (S**)malloc(5 * sizeof(S));
for (int i = 0; i < 5; ++i)
    arr[i] = (S*)malloc(5 * sizeof(S));

【问题讨论】:

  • S 中添加一个不可复制的成员,然后malloc 代码就惨败了。
  • 动态分配这个数组的正确方式是std::vector&lt;std::vector&lt;S&gt;&gt;。您的new 版本属于“技术上工作”,malloc 属于“未定义行为”。
  • @OP 这个“简单结构”使用malloc 失败:struct S { std::string str; };。那一个 std::string 成员会导致 malloc 代码损坏。
  • @PaulMcKenzie 但我不在这里使用std::string
  • @Quentin malloc 有什么问题?

标签: c++ arrays malloc dynamic-memory-allocation new-operator


【解决方案1】:
  1. 是的,这是正确的方法。不,不需要使用sizeof(S)
  2. 您的代码不正确。通常,如果 struct S 具有不可复制的成员,则不应使用 malloc,但如果 S 满足该条件,则您的代码应如下所示:
S** arr = (S**)malloc(5 * sizeof(S*));
for (int i = 0; i < 5; ++i)
    arr[i] = (S*)malloc(5 * sizeof(S));

但是在 C++ 中使用 malloc 被认为是不好的做法。如果可以的话,我会尝试使用std::vector 重写它。 当然不要忘记使用delete/free清除内存以防使用new/malloc

【讨论】:

  • 你真的应该提到如果S 更改为具有非平凡可复制的成员,malloc 代码将被破坏。
猜你喜欢
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
相关资源
最近更新 更多