I am learning pointers and structures in C.
In this process I am stuck with a problem, consider the following code :
#include <stdio.h>
#include <stdlib.h>
struct data{
int i;
};
void test(struct data *, int);
int main(){
struct data *head = NULL;
test(head, 100);
printf("head->i :%d\n",head->i); // Should print 100, but it's NOT.
return 0;
}
void test(struct data *head, int i){
struct data *new = (struct data *)malloc(sizeof(struct data));
new->i = 10;
head = new;
}
But instead of printing 100, the programming is throwing a Segmentation Fault.
When I modify the code as follows :
#include <stdio.h>
#include <stdlib.h>
struct data{
int i;
};
struct data *head = NULL;
void test(int );
int main(){
test(100);
printf("head->i :%d\n",head->i); // It prints 100 WITH EASE!
return 0;
}
void test(int i){
struct data *new = (struct data *)malloc(sizeof(struct data));
new->i = 10;
head = new;
}
All I did in the above code was declare the head pointer globally.
How does that make any difference?
Can someone please explain me Why?