EDIT
Thank you everyone, I now understand that I was passing by value. But now I have another doubt regarding this.
Here, the append function's task involves changing the end pointer.
Both the arguments of append function are pointer's, in 1st case, 1st argument is &pt1 and 2nd argument is &pt2.
The function makes a copy of end pointer which has type of struct point.
Since &pt1 is passed then this duplicate end pointer has x component as 1 and y component as -1 and next component as NULL.
Now we change this copy's next component to newpt pointer and return the newpt pointer.
Back to the the main func,
original end pointer now has the value of &pt2.
Acc to what I understood,
end->next = newpt; shouldn't produce any change in the original end pointer in main.
So then why do I get a liked list.
Here, is the code:
struct point{
int x;
int y;
struct point *next;
};
void printPoints(struct point *);
void printPoint(struct point *);
struct point * append(struct point *, struct point *);
void main(){
struct point pt1={1,-1,NULL};
struct point pt2={2,-2,NULL};
struct point pt3={3,-3,NULL};
struct point *start, *end;
start=end=&pt1;
end=append(end,&pt2);
end=append(end,&pt3);
printPoints(start);
}
void printPoint(struct point *ptr){
printf("(%d, %d)\n", ptr->x, ptr->y);
}
struct point * append(struct point *end, struct point *newpt){
end->next=newpt;
return newpt;
}
void printPoints(struct point *start){
while(start!=NULL){
printPoint(start);
start=start->next;
}
}
What I get:
(1, -1)
(2, -2)
(3, -3)
What I think I should get:
(1, -1)
Original Question
I have a simple program to insert elements at the end of the linked list using a function call.
My Code:
struct Date{
int data;
struct Date *next;
};
void print(struct Date *date_head);
void add(int date, struct Date *date_head);
int main(){
struct Date *date_head=NULL;
add(12,date_head);
add(15,date_head);
}
void print(struct Date *date_head){
struct Date *ptr=date_head;
printf("Dates: ");
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
void add(int date, struct Date *date_head){
//newDate
struct Date *newDate;
newDate = (struct Date *)malloc(sizeof(struct Date));
newDate->data=date;
newDate->next=NULL;
//inserting newDate at end
struct Date *date_ptr;
date_ptr=date_head;
if (date_ptr==NULL) {date_head=newDate;}
else{
while(date_ptr->next!=NULL){
date_ptr=date_ptr->next;
}
date_ptr->next=newDate;
}
print(date_head);
}
What I want:
Dates: 12
Dates: 12 15
What I get:
Dates: 12
Dates: 15
The struct becomes NULL outside the add function. Even when I am using pointers. Why?
I dont know if I am making a beginner mistake.