c -为什么我不能在下面的程序中初始化指向变量的指针的值


#include<Stdio.h>
int main()
{
int a ,b;
int *p;
int *q;
printf("enter the value of a and b");
scanf("%d%d",&a,&b);
p = &a;
q = &b;
printf("value of a and b is %d and %d",a,b);
a = *q;
b = *p;
printf("value of a and b is %d and %d",a,b);
}

i不能改变b的值,即使将其重新定义为指针p。

输出

您实际上是为b赋值,但由于您已经更改了a的值,因此您不会注意到赋值,假设您为a输入4,为b输入5:

a = *q;  // q points at b, which is 5, so a = 5
b = *p;  // p points at a, which is now 5, so, b = 5

要交换值,您可以这样做:

int tmp = a; // store the value of a, 4
a = b;       // assign, a = 5
b = tmp;     // assign, b = 4 (the stored value)

或者用它创建一个函数:

void swap(int *lhs, int *rhs) {
int tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}

并命名为:

swap(&a, &b);