struct 指针如何区分同一指针的使用?
How does a struct pointer differentiate between the use of the same pointer?
这是极客给极客的一个例子。最后一个例子是 root->left->left = new Node(4);
我想知道左节点如何保留其旧值,并能够使用相同的结构变量连接到新值。每次调用“new Node()”时是否创建另一个内存块或什么?我很困惑。
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
// val is the key or the value that
// has to be added to the data part
Node(int val)
{
data = val;
// Left and right child for node
// will be initialized to null
left = NULL;
right = NULL;
}
};
int main()
{
/*create root*/
struct Node* root = new Node(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
root->left = new Node(2);
root->right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = new Node(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/
return 0;
}
root->left = new Node(2);
和 root->left->left = new Node(4);
都在内存中创建新的节点对象,所以你有问题
Is each time the "new Node()" being called its creating another block of memory or what?
有点准确。
一开始,root是一个Node对象,data值为1,left值为NULL。它的左指针没有指向任何东西。语句 root->left = new Node(2);
将根左指针设置为新节点的地址。这个新节点的数据值为 2,左值为 NULL。假设这个新节点有一个名称,它的名称是 A。表达式 root->left->left
从左到右求值,因此 root->left
是节点 A,因此表达式变为 A->left
。 A->left
当前为 NULL。 root->left->left = new Node(4);
执行后,A 的左指针现在指向数据值为 4 的新节点。
这是极客给极客的一个例子。最后一个例子是 root->left->left = new Node(4);
我想知道左节点如何保留其旧值,并能够使用相同的结构变量连接到新值。每次调用“new Node()”时是否创建另一个内存块或什么?我很困惑。
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
// val is the key or the value that
// has to be added to the data part
Node(int val)
{
data = val;
// Left and right child for node
// will be initialized to null
left = NULL;
right = NULL;
}
};
int main()
{
/*create root*/
struct Node* root = new Node(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
root->left = new Node(2);
root->right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = new Node(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/
return 0;
}
root->left = new Node(2);
和 root->left->left = new Node(4);
都在内存中创建新的节点对象,所以你有问题
Is each time the "new Node()" being called its creating another block of memory or what?
有点准确。
一开始,root是一个Node对象,data值为1,left值为NULL。它的左指针没有指向任何东西。语句 root->left = new Node(2);
将根左指针设置为新节点的地址。这个新节点的数据值为 2,左值为 NULL。假设这个新节点有一个名称,它的名称是 A。表达式 root->left->left
从左到右求值,因此 root->left
是节点 A,因此表达式变为 A->left
。 A->left
当前为 NULL。 root->left->left = new Node(4);
执行后,A 的左指针现在指向数据值为 4 的新节点。