【问题标题】:convert malloc to new c++ for struct将 malloc 转换为新的 c++ for struct
【发布时间】:2014-08-08 19:52:01
【问题描述】:

我有这个结构:

struct problem
{
int length;
struct node **x;
};     

我创建了一个这样的结构:

struct problem prob;

我可以在 C 中做到这一点:

prob.x = Malloc(struct node *,prob.length);

但是我如何使用 new 以 c++ 风格做到这一点?为什么?

【问题讨论】:

  • 向我们展示失败的代码。
  • Malloc 是你自己的函数吗? malloc 仅适用于 1 个参数
  • prob.x = new node*[prob.length] 呢?
  • “……为什么?”好问题。将代码保留为 C,或将其更改为适当的 C++,例如:struct problem { std::vector<std::unique_ptr<node>> x; };
  • 把它放在问题中。

标签: c++ memory-management malloc


【解决方案1】:

在 C++ 中,可以通过这个来实现。

std::vector<node *> problem(length);

您展示的代码有效地模拟了vector 的一小部分功能。即,一个知道其大小的类数组容器。

【讨论】:

    【解决方案2】:

    好的,这段代码可能有效,请注意,您不再持有指向指针的指针,而是一个简单的数组 - 这可能适用于您尝试做的事情,也可能不适用:

    typedef struct tagnode
    {
      ...
    } node;
    
    typedef struct tagproblem
    {
    int length;
    node *x;
    
    tagproblem(int len) : length(len)
     {
      x = new node[length];
     }
    ~tagproblem()
     {
      delete [] x;
     }
    } problem;
    
    //Now create...
    problem = new problem(2);
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多