指针如何变化

How is the pointer changing?

本文关键字:变化 何变化 指针      更新时间:2023-10-16

我找不到有关为什么指针在以下代码中更改的解释。

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

如http:///ideone.com/tieju4

所示,它在其他版本的G 上工作。

我缺少什么?

这看起来像未定义的行为,因为您正在写入未分配的内存,并在以下两个行上分配过多。

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;