这是第一个代码
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x=10,y=20;
printf("Before swap x = %d and y = %d\n",x,y);
swap(&x,&y);
printf("After swap x = %d and y = %d",x,y);
return 0;
}
这是第二个
#include<stdio.h>
#include<conio.h>
int main()
{
int x=10,y=20;
printf("Before swap x = %d and y = %d\n",x,y);
int *a = &a;
int *b = &b;
int temp = *a;
*a = *b;
*b = temp;
printf("After swap x = %d and y = %d",x,y);
return 0;
}
我尝试使用指针交换 x 和 y 的值,在第一个代码中我使用了一个函数,在第二个代码中我尝试做同样的事情但没有使用函数,第一个代码有效,但第二个代码没有。
在第一个示例中,您获取
x
的地址并将其作为参数传递给 swap()
函数。
在第二个示例中,您使用
a
的地址!是的,这是 C 的一个奇怪的特性:您可以在其初始赋值中使用变量:
int * a = &a; // takes the address of `a` and assigns it to `a`
如果您调高编译器警告,它会向您抱怨您正在将
int **
分配给 int *
。
你的意思是获取
x
的地址,就像你的第一个例子一样:
int * a = &x;
确保打开警告:
-Wall -Wextra
/W3
编译代码时,找出最上面的错误或警告,修复它,并继续这样做,直到可以编译而不生成任何警告或错误。
学习 C 语言编程有点艰难,但这是值得的!