I'm trying to learn data structures in C and I'm stuck at the first function I made.
If I run this nothing happens.
I get no errors but the program doesn't print anything.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
void insert(int data, node *head){
node *new_node = malloc(sizeof(node));
new_node->data = data;
head = new_node;
}
int main(){
node *head = NULL;
insert(8, head);
printf("head.data: %d\n", head->data);
}
But if I put the code from the function insert in the main function it works.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
int main(){
node *head = NULL;
node *new_node = malloc(sizeof(node));
new_node->data = 5;
head = new_node;
printf("head.data: %d\n", head->data);
}
Do I not know how to use functions in C or what is the problem with my first code?
headis passed by value to theinsertfunction, which means that any assignment to the localheadvariable in that function does not affect the otherheadvariable inmain.