Mykybo
Mykybo

Reputation: 1499

C pointers weird behaviour

I am having trouble comprehending why this works:

int main() {
    int test = 4;
    int *bar = &test;
    int **out = &bar;
    printf("%d\n", **out);
    return 0;
}

but this doesn't:

void foo(int *src, int **out) {
    out = &src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int **out;
    foo(bar, out);
    printf("%d\n", **out);
    return 0;
}

The second snippet throws "Segmentation fault". To me it seems they do the same thing. Can someone explain please?

Edit: (updated code based on answers):

void foo(int *src, int **out) {
    out = &src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int *out;
    foo(bar, &out);
    printf("%d\n", *out);
    return 0;
}

Then why does this not work?

Solved: (I had to think through what I really wanted to do), this is the result:

void foo(int *src, int **out) {
    *out = src;
}

int main() {
    int test = 4;
    int *bar = &test;
    int *out;
    foo(bar, &out);
    printf("%d\n", *out);
    return 0;
}

Upvotes: 0

Views: 77

Answers (2)

Scott Hunter
Scott Hunter

Reputation: 49803

In the second, the variable out in main is not affected by the assignment made inside of foo.

In your edit, you need to have foo assign to what out in it points to:

*out = src;

Upvotes: 4

user2100815
user2100815

Reputation:

Things are passed into functions by value. Changing the value in the function changes nothing in the outside world.

Upvotes: 0

Related Questions