0

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?

Still Learning
  • 441
  • 1
  • 4
  • 10
  • Assigning `head` inside `test` does not change the value of `head` in the `main`, because pointers are passed by value (just like everything else). Change the function to return `struct data` and assign it to the `head` in the `main`, or take `head` by double pointer. – Sergey Kalinichenko May 23 '17 at 16:22
  • Of course there is no error in the `test` function. The problem is in the design of the interaction between `test` function and `main` function. – Sergey Kalinichenko May 23 '17 at 16:24
  • 1
    Until now, I thought pointers were passed by reference. I was confused earlier, but after reading [this](https://stackoverflow.com/questions/4426474/is-passing-pointer-argument-pass-by-value-in-c ). – Still Learning May 23 '17 at 16:28
  • That's C++. C does not have reference types. – Sergey Kalinichenko May 23 '17 at 16:30
  • 1
    Pointer variables are always passed by reference because they contain an address. The difference between a pointer variable and a reference variable is that the reference variable is pointing an address that cannot be changed, therefore it is not a natural pointer. C language does not have reference variables, they are a C++ concept. – Vic May 23 '17 at 17:03

0 Answers0