C pointers - Point to the same address

2020-06-05 01:55发布

#include <stdio.h>
#include <stdlib.h>

void foo(int *a, int *b);

void foo(int *a, int *b) {
    *a = 5;
    *b = 6;
    a = b;
}

int main(void) {
    int a, b;
    foo(&a, &b);
    printf("%d, %d", a, b);
    return 0;
}

Why a = b (foo) doesn't work? printf outputs "5, 6" Thank you.

标签: c pointers
7条回答
冷血范
2楼-- · 2020-06-05 02:25

a and b are local to the function foo (they are on the stack), when program returns from the function data on the stack is lost. when you assign b to a, you are only modifying memory addresses on the stack, not their values.

查看更多
登录 后发表回答