我在 C++ 上尝试链表,当我尝试打印列表的数据时,它给出了有趣的结果,告诉我列表为空。当我在 main 中打印变量的地址并在函数中打印同一变量的参数地址时,它会给出不同的结果。谁能帮我解释一下,谢谢!这是代码:
#include <iostream>
using namespace std;
typedef struct link_node{
int data;
link_node* next;
};
void iter(link_node* head){
link_node* cur = head;
cout<<"The address of head in function: "<<&head<<endl;
while(cur!=NULL){
cur = cur->next;
cout<<cur->data<<' ';
}
}
link_node *create(int a){
link_node* head;
link_node* cur;
head =(link_node*) malloc(sizeof(link_node));
cur = head;
for(int i=a;i<a+10;i+=2){
link_node * node = (link_node*) malloc(sizeof(link_node));
node->data = i;
cur->next = node;
cur = node;
}
cur->next = NULL;
return head;
}
int main(){
link_node* head_1 = create(0);
link_node* head_2 = create(1);
link_node* result = (link_node*) malloc(sizeof(link_node));
cout<<"The address of head_1: "<<&head_1<<endl;
iter(head_1);
return 0;
}
这是程序的输出:
The address of head_1: 0x61ff04
The address of head in function: 0x61fef0
0 2 4 6 8
谢谢!
head
和head_1
是两个不同的变量,所以它们有两个不同的地址。但是这些变量的值也是地址(或指针),并且这些值是相同的。
在处理指针时,很容易混淆变量的地址和变量的值,因为它们都是指针(但指针类型不同)。
换句话说,所有变量都有地址,但只有指针变量的值也是地址。
试试这个代码
cout<<"The value of the head pointer: "<<head<<endl;
cout<<"The value of the head_1 pointer: "<<head_1<<endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句