Why can't we pass a pointer by reference in C?

I am learning C. I wrote code to create a linked list when I encountered a segmentation error. I found a solution to my problem in this question. I tried to pass a pointer by reference. The decision says that we cannot do this. We must pass a pointer to a pointer. This solution worked for me. However, I do not understand why this is so. Can anyone explain the reason?

+4
source share
1 answer

From the C programming language - second edition (K & R 2):

5.2 Function pointers and arguments

C , .

...

.

, :

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;
}

:

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;
}

, int , int, .

+5

Source: https://habr.com/ru/post/1543333/


All Articles