Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't we pass the pointer by reference in C?

I am learning C. I was writing code to create a linked list when i came across a segmentation fault. I found a solution to my problem in this question. I was trying to pass a pointer by reference. The solution says that we can't do so. We have to pass a pointer to a pointer. This solution worked for me. However, I don't understand why is it so. Can anyone tell the reason?

like image 651
user3075740 Avatar asked Jun 05 '14 05:06

user3075740


1 Answers

From The C Programming Language - Second Edition (K&R 2):

5.2 Pointers and Function Arguments

Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function.

...

Pointer arguments enable a function to access and change objects in the function that called it.

If you understand that:

void fn1(int x) {
    x = 5; /* a in main is not affected */
}
void fn2(int *x) {
    *x = 5; /* a in main is affected */
}
int main(void) {
    int a;

    fn1(a);
    fn2(&a);
    return 0;
}

for the same reason:

void fn1(element *x) {
    x = malloc(sizeof(element)); /* a in main is not affected */
}
void fn2(element **x) {
    *x = malloc(sizeof(element)); /* a in main is affected */
}
int main(void) {
    element *a;

    fn1(a);
    fn2(&a);
    return 0;
}

As you can see, there is no difference between an int and a pointer to element, in the first example you need to pass a pointer to int, in the second one you need to pass a pointer to pointer to element.

like image 70
David Ranieri Avatar answered Oct 09 '22 20:10

David Ranieri