动态分配的二维数组中使用的用户定义类型

User defined type used in dynamic allocated 2d array

提问人:Michal 提问时间:10/26/2021 更新时间:10/26/2021 访问量:110

问:

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

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

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

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

我的问题是:

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

评论

1赞 PaulMcKenzie 10/26/2021
将一个非平凡的可复制成员插入,该代码会惨遭失败。Smalloc
1赞 Quentin 10/26/2021
动态分配此数组的正确方法是 。您的版本属于“技术上有效”,而版本属于“未定义的行为”。std::vector<std::vector<S>>newmalloc
0赞 PaulMcKenzie 10/26/2021
@OP 这个“简单结构”使用 : 失败。该单个成员使 malloc 代码损坏。mallocstruct S { std::string str; };std::string
0赞 Michal 10/26/2021
@PaulMcKenzie但我在这里不用。std::string
0赞 Michal 10/26/2021
@Quentin 这里有什么问题?malloc

答:

4赞 Deumaudit 10/26/2021 #1
  1. 是的,这是正确的方法。不,没有必要使用sizeof(S)
  2. 您的代码不正确。通常,如果具有非平凡的可复制成员,则不应使用 if,但如果 S 满足该要求,则代码应如下所示:mallocstruct 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 重写它。 当然,不要忘记清除内存 / 以防使用deletefreenew/malloc

评论

0赞 PaulMcKenzie 10/26/2021
你真的应该提到,如果更改为具有非平凡的可复制成员,代码就会被破坏。mallocS