I am trying to create one singly linked list and swap two int element in sub-
function.
swap(int *a,int *b) , the type of parameter is int *,and it can work successfully.build_sll(node *head), the singly linked list won't be created successfully.build_sll(node *&head),and it will be created singly linked list successfully.Confused with:
function swap(int *a,int *b) passed the address of a b, I could modify the value of a b .
function build_sll(node *head) passed only the value of pointer head. I could not modify the value of head.
why here does not pass the address of head. The only difference between them is their data type.
while set build_sll(node *head), after GDB my code, and I found that all the node object have been created successfully. In main if I visited the allocated address, it does record the node information. how to delete memory in such case.
See my code to make clear my question.
#include<iostream>
#include<cstdlib>
#include<memory.h>
using namespace std;
typedef struct node{
int num;
struct node * next;
node(int num,struct node * next)
{
this->num = num;
this->next = next;
}
}node;
void build_sll(node *&head);
void del_memory(node *&head);
void travel_sll(node *head);
void swap(int *,int *);
int main()
{
int a =10 ,b = 5;
node *head = NULL;
build_sll(head);
travel_sll(head);
del_memory(head);
swap(&a,&b);
cout << a <<" "<< b <<"\n";
exit(0);
}
void build_sll(node *&head)
{
head = new node(0,NULL);
node * tail = head;
for(int index = 1 ; index < 8;index++)
{
node * temp = new node(index,NULL);
tail -> next = temp;
tail = temp;
}
}
void travel_sll(node *head)
{
if(head)
{
head = head -> next;
while(head)
{
cout << head->num <<"\n";
head = head -> next ;
}
}
}
void del_memory(node *&head)
{
delete [] head;
}
void swap(int *a,int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
function
swap(int *a,int *b)passed the address of a b, I could modify the value of a b . functionbuild_sll(node *head)passed only the value of pointer head. I could not modify the value of head. why here does not pass the address of head. The only difference between them is their data type.
In function swap, you want to modify/access the value of int so passing int * or int & would work. Passing arguments of type int is good for reading the value of arguments, but if you change it, only local copy is updated and not the values with which you called the function.
In function build_sll you want to change the argument of type node *. So you should pass argument of type node ** or node *& to ensure you can change the value with with it was called. Passing node * would only change the local copy (in called function) and original value in the callee function would remain unchanged.
Your options are:
node * build_sll(node *);node * build_sll(node *&);node * build_sll(node **); etcIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With