指针如何变化
How is the pointer changing?
我找不到有关为什么指针在以下代码中更改的解释。
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;
相关文章:
- C++取消引用指针.为什么会发生变化
- 为什么在读取文件大小时文件IO速度会发生变化
- 为什么cudaMemGetInfo报告设备内存总量的变化
- 如何避免LED在循环状态变化中闪烁?
- 当 I2C 值在C++中发生变化时收到通知
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- 当我调用对象的方法时,对象的成员会发生变化
- 为什么向量内部的指针在从函数返回时会发生变化?
- 如何在 c++ 中循环中使用频率变化的声音?
- 为什么 C++ 中的零会发生变化
- 为什么我的全局变量似乎没有变化?
- 使用 IMFSinkWriter 编码的视频的播放速度会根据宽度而变化
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么预减量会导致奇怪的变化?
- MATLAB:跟踪imufilter对象中的状态变化
- 当父小部件大小发生变化时,如何更改子小部件的大小?
- 我正在将一个 std::string 传递给一个 boost 函数,该函数对该类型进行常量引用,但该值发生了变化
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 为什么使用默认构造函数"{}"而不是"= default"存在性能变化?
- 为什么数据类型的大小会随着操作系统的变化而变化