C pointers - Point to the same address

后端 未结 7 1603
野趣味
野趣味 2021-02-10 15:38
#include 
#include 

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

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

int main(void) {
    int          


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-10 16:15

    It does work; it just doesn't do what you think it does.

    In foo(), a = b changes the pointer a to point to whatever b points to. It has no effect on anything outside of the function; it only changes the pointers.

    If you want to change the value of the int pointed to by a to be the same as the value of the int pointed to by b, you need to use *a = *b, similar to how you do the assignments in the function already.

提交回复
热议问题