我无法在下面的代码中找到指针变化原因的解释。
struct node{
int val;
node *left;
node *right;
}*root;
int main() {
node *tmp = (node *)malloc(sizeof(node *));
tmp->val = 5;
tmp->left = NULL;
tmp->right = NULL;
root = tmp;
node *t = (node *)malloc(sizeof(node *));
cout<<"earlier: "<<&root->right<<" "<<root->right<<endl;
t->val = 4;
cout<<"after: "<<&root->right<<" "<<root->right<<endl;
t->left = NULL;
t->right = NULL;
root->left = t;
return 0;
}
输出是-
earlier: 0x7fb812404ac0 0x0
after: 0x7fb812404ac0 0x4
root->right
的值已经改变,不再是NULL
。
注意 - 我在我的 OSX g++ 编译器中遇到这个错误
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
它在其他版本的 g++ 上按预期工作,如 http://ideone.com/tIEjU4 所示
我错过了什么?
最佳答案
这看起来像是未定义的行为,因为您在以下两行中写入分配太小的未分配内存。
node *tmp = (node *)malloc(sizeof(node *));
node *t = (node *)malloc(sizeof(node *));
相反,您需要为节点分配足够的资源。
node *tmp = (node *)malloc(sizeof(node));
node *t = (node *)malloc(sizeof(node));
正如@Mat 所指出的,您可能想在这里使用new
,因为您已经将问题标记为c++
。
node *tmp = new node;
node *t = new node;
关于c++ - 指针如何变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30012063/