指针是如何变化的?

hya*_*des 0 c++ pointers

我无法找到解释为什么指针在下面的代码中发生变化的原因.

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;
}
Run Code Online (Sandbox Code Playgroud)

输出是 -

earlier: 0x7fb812404ac0 0x0
after: 0x7fb812404ac0 0x4
Run Code Online (Sandbox Code Playgroud)

价值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
Run Code Online (Sandbox Code Playgroud)

它在其他版本的g ++上按预期工作,如http://ideone.com/tIEjU4所示

我错过了什么?

mer*_*011 5

这看起来像未定义的行为,因为您在以下两行中使用过小的分配写入未分配的内存.

node *tmp = (node *)malloc(sizeof(node *));
node *t = (node *)malloc(sizeof(node *));
Run Code Online (Sandbox Code Playgroud)

相反,您需要为节点分配足够的空间.

node *tmp = (node *)malloc(sizeof(node));
node *t = (node *)malloc(sizeof(node));
Run Code Online (Sandbox Code Playgroud)

正如@Mat指出的那样,你可能想在new这里使用,因为你已经标记了这个问题c++.

node *tmp = new node;
node *t = new node;
Run Code Online (Sandbox Code Playgroud)