0
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node{
    int data;
    struct node* link;
};
struct node *head1=NULL;
struct node *tail1;
void insertAtLast(struct node* head,struct node* tail,int num){
    struct node* newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=num;
    newnode->link=NULL;
    if (head==NULL){
        printf("Came here");
        head=newnode;
        tail=newnode;
        if (head1==newnode){
            printf("Head1 changes");
        }
    }
    else{
        tail->link=newnode;
        tail=newnode;
    }
}
int main(){
    int n1;
    printf("Enter the number of elements in list1: ");
    scanf("%d",&n1);
    int i,t;
    printf("Enter the elements- ");
    for (i=0;i<n1;i++){
        scanf("%d",&t);
        insertAtLast(head1,tail1,t);
    }
    struct node* temp=head1;
    while (temp!=NULL){
        printf("%d",temp->data);
        temp=temp->link;
    }
    return 0;
}

The value of head1 is not changing even though I pass by reference. Even after assigning head1 and tail1 as pointer, they are not modified when they are passed by reference and modified inside the function.

  • 1
    C does not have "pass by reference", a *copy* of the pointer is passed. If you want to modify the original, you can either pass a pointer-to-the-pointer so that it can be modified, or return the new value as the function value, which the caller then assigns to the original variable. – Weather Vane Mar 06 '20 at 18:08
  • 1
    You're not passing it by reference. – Barmar Mar 06 '20 at 18:08

0 Answers0