通常在交换函数中,我们希望看到被调用函数中交换的值。在这里,我试着看看很少的操作是如何与指针一起进行的,但我得到了错误。
我试着寻找通过引用传递的标签,但我没有找到有用的东西,所以我在这里发布我的代码。
请告诉我出现此错误的原因。
#include<stdio.h>
void swap(int *a,int *b)
{
int *temp;/*points to a garbage location containing a
garbage value*/
*temp=*a; /*swapping values pointed by pointer */
*a=*b;
*b=*temp;
printf("%d %d %d\n ",*a,*b,*temp);
}
int main()
{
int x=10;
int y=20;
printf("ADdress: %u %u\n",&x,&y);
swap(&x,&y); /* passing address of x and y to function */
printf("ADdress: %u %u\n",&x,&y);
printf("%d %d\n",x,y);
return(0);
}
在这里,我将 temp 作为指针变量,而不是我们使用普通 temp 变量的常规约定,我希望它能正常工作,但事实并非如此。 x 和 y 将它们的地址传递给交换函数。
它和swap函数有什么区别?
我是否错误地解释了这段代码?
最佳答案
因为你没有为指针int *temp;
分配空间
您有两种选择以正确的方式做到这一点..
1) 要么使用 int
int temp;/*points to a garbage location containing a
garbage value*/
temp=*a; /*swapping values pointed by pointer */
*a=*b;
*b=temp;
或者,
2) 使用malloc()
int *temp = malloc(sizof(int));
*temp=*a; /*swapping values pointed by pointer */
*a=*b;
*b=*temp;
关于c - 为什么 C 代码中的引用调用不能交换 2 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265692/