0
#include <stdio.h>
#include <stdlib.h>

typedef struct node* Node;

struct node{
int a;
struct node* next;
};

void insertAtBeginning(Node head){
Node temp = malloc(sizeof(struct node));
temp->a = 10;
temp->next = head;
head = temp;
}

int main(){
Node one = malloc(sizeof(struct node));
one->a = 11;
Node head = one;
insertAtBeginning(head);
printf("%d",head->a);

}

Expected : 10

Received : 11

I'm passing pointer(struct node* head) to function why is it not reflecting back in main method?

2
  • Passing a pointer to a function provides a way for the function to modify the thing the pointer points to. It does not provide a way for the function to modify the caller's copy of the pointer itself. If you want that, you can have the function receive a pointer to the pointer instead. Commented Feb 20 at 14:22
  • 1
    Also, do not hide pointer nature behind a typedef (i.e. your Node), except possibly in very special circumstances. Disguising the number of levels of indirection is confusing, much more than expressing object pointer types explicitly creates any kind of trouble. Commented Feb 20 at 14:26

1 Answer 1

0

You need to pass in pointer of pinter:

#include <stdio.h>
#include <stdlib.h>

typedef struct node* Node;

struct node{
    int a;
    struct node* next;
};

void insertAtBeginning(Node *head){
    Node temp = malloc(sizeof(struct node));
    temp->a = 10;
    temp->next = head;
    *head = temp;
}

int main(){
    Node one = malloc(sizeof(struct node));
    one->a = 11;
    Node head = one;
    insertAtBeginning(&head);
    printf("%d",head->a);

}
Sign up to request clarification or add additional context in comments.

2 Comments

C does not support reference, for C++ you may also pass the pointer by reference. Also see stackoverflow.com/questions/55401073/…
Better to avoid explicit types in malloc calls, e.g., Node one = malloc(sizeof *one);. Also better to avoid typedefs of pointers unless you are creating an opaque data type, e.g., typedef struct node Better; /*...*/ Better *two = malloc(sizeof *two);.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.