I was trying linked list on C++ and when I try to print the data of the list, it gives funny result which tells me that the list is null. When I print the address of the variable in main and print the address of the parameter of the same variable in the function, it gives different results. Could anyone please explain it for me, thank you! Here is the code:
#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;
}
And here is the output of the program:
The address of head_1: 0x61ff04
The address of head in function: 0x61fef0
0 2 4 6 8
Thanks!