简体   繁体   English

为结构分配内存

[英]Allocating memory to a struct

Example例子

struct Node
{
    int data;
    Node *left;
    Node *right;
};

void allocate(const int data, Node *&n)
{
    ;
    // How do we allocate memory here?
    //n = new Node(data, nullptr, nullptr);
}

void remove(Node *&n) { delete n; }

int main()
{
    Node *n;
    allocate(1, n);
    remove(n);
}


What is the proper way to allocate memory to n in the function allocate . 在函数allocaten分配内存的正确方法是什么。 I am not sure how to properly initialize a struct. 我不确定如何正确初始化结构。

You may do this in this way:你可以这样做:

n = new Node {data, nullptr, nullptr};

Complete Code:完整代码:

struct Node
{
    int data;
    Node *left;
    Node *right;
};

void allocate(const int data, Node *&n)
{
    ;
    // How do we allocate memory here?
    n = new Node{data, nullptr, nullptr};
}

void remove(Node *&n) { delete n; }

int main()
{
    Node *n;
    allocate(1, n);
    remove(n);
}

Suggestions :建议

1) In C++, struct can also have constructors. 1)在C++中,struct可以有构造函数。 So, instead of using a separate function for this, you must define constructor.因此,您必须定义构造函数,而不是为此使用单独的函数。

2) Never use naked new . 2)永远不要使用裸new You must consider smart pointers like unique_ptr and shared_ptr你必须考虑像unique_ptrshared_ptr这样的智能指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM