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

后端 未结 1 406
甜味超标
甜味超标 2020-12-06 21:21

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

1条回答
  •  一整个雨季
    2020-12-06 21:44

    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.

    0 讨论(0)
提交回复
热议问题