[英]Allocating memory to a struct
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);
}
n
in the function allocate
.
allocate
为n
分配内存的正确方法是什么。
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_ptr
和shared_ptr
这样的智能指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.