无法弄清楚指针行为
Unable to figure out pointers behaviour
我无法弄清楚为什么temp->next=NULL
打破原始链接列表
我的代码在这里:
struct Node{
int data;
Node* next;
};
Node* createNode(int data)
{
Node* temp=new Node;
temp->data=data;
temp->next=NULL;
return temp;
}
int main()
{
Node* root=createNode(1);
root->next=createNode(2);
root->next->next=createNode(3);
display(root);
cout<<"nAddress of root = "<<&root<<"-> "<<&(root->next)<<"-> "<<&(root->next->next);
Node* temp=root;
temp->next=NULL; //Trying to set next pointer to Null in temp list but instead it is impacting the original list by nullifying the next node. Why is it so ?
display(temp);
cout<<"nAddress of temp = "<<&temp<<"-> "<<&(temp->next);
display(root); // Original list broke
}
输出:
Linked list => 1->2->3
Address of root = 0x7ffd3afbc2f0-> 0x5605aff6cc28-> 0x5605aff6cc48
Linked list => 1
Address of temp = 0x7ffd3afbc2f8-> 0x5605aff6cc28
Linked list => 1
考虑指针int* ptr;
和整数int var;
。以同样的方式, &var
是整数的地址,与其值不同, &ptr
是指针的地址,与其值不同( what what ,它指向(。
表达式Node* temp=root;
正在创建一个指针temp
,其值与root
相同,它们是指同一对象。temp
和root
是不同的对象,并且具有不同的地址(&root
和&temp
不同(,但是它们具有相同的值(root
和temp
相等(。因此,temp->next
和root->next
是相同的指针。更改一个会改变另一个。
在您的示例中,只有一个链接列表, root
和 temp
都参考。
指针只是指向内存中的一个位置,因此他们的名字。当您这样做时:
Node* temp=root;
您创建一个指向与指针root
相同内存位置的指针temp
。因此:
temp->next=NULL;
和此:
root->next=NULL;
做完全相同的事情,因为temp->next
和root->next
是相同的。
相关文章:
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 弄清楚如何在C++中将整数读入 ASCII
- 写一个分数类,我无法弄清楚这些错误
- 分段错误(核心转储)但无法弄清楚
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 为什么我的编译器无法弄清楚这种转换,它何时存在?
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 循环不继续无法弄清楚为什么
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 无法弄清楚为什么没有调用重载运算符 []
- 无法弄清楚如何使用 c++ 中的链表按从 a 到 z 的顺序显示字母
- 我无法弄清楚"对Winmain@16错误的未定义引用"
- 谁能弄清楚为什么我的循环会失败?
- 试图弄清楚我需要做哪些更改才能使代码正常工作.使用Visual Studio
- 使用指针和引用,无法弄清楚为什么DFS无限重复
- 无法弄清楚指针行为
- C++ 简单的指针错误无法弄清楚为什么?
- 无法弄清楚此示例中的指针逻辑
- 弄清楚多态类型的c++指针是如何工作的
- 我的指向 std::string 对象的指针列表无法正常工作,我无法弄清楚为什么