Reputation: 9
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
int main(int argc, char *argv[]) {
struct node *p;
p = NULL;
Append(&p , 1); // Append adds a node to the end of linked list
Append(&p , 2);
Append(&p , 3);
AddatBeginning (p, 100);
Display(p); // Displays Elements of Linked List
return 0;
}
// The function AddatBeginning adds a node at the beginning of linked list 'p'
void AddatBeginning (struct node *p, int num)
{
struct node *f, *temp = NULL;
f = p;
temp = (struct node *)malloc (sizeof(struct node));
temp->data = num;
temp->link = f;
p=temp;
}
I ran the code in DevC++ but not getting the expected output - 100, 1, 2, 3.
The output I got is 1,2,3.
On debugging the code, I found that the expression "p=temp;" in function "AddatBeginning" is not working. P is not pointing where temp is pointing after the execution of statement. Why is it so?
Upvotes: 0
Views: 96
Reputation: 311088
You are passing the pointer p
by value
AddatBeginning (p, 100);
It means that the function deals with a copy of the original passed pointer. Any changes of the copy like that
p=temp;
leave the original pointer unchanged.
That is a function parameter that is a local variable of the function is initialized by the value of the passed argument and within the function you deal with this separate local variable.
You need to pass the pointer p
by reference. In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the passed pointer you have a direct access to the original object that in turn can be a pointer.
So the function will look the following way
int AddatBeginning (struct node **p, int num)
{
struct *temp = malloc( sizeof( struct node ) );
int success = temp != NULL;
if ( success )
{
temp->data = num;
temp->link = *p;
*p = temp;
}
return success;
}
and can be called like
AddatBeginning( &p, 100 );
or
if ( !AddatBeginning( &p, 100 ) )
{
// error message
}
By the way the function Append
Append(&p , 1);
^^
accepts the original pointer by reference.:)
Pay attention to that the called functions shall be declared in the program before their usage.
Upvotes: 3