gpt4 book ai didi

c - 为什么 C 代码中的引用调用不能交换 2 个值?

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:30 26 4
gpt4 key购买 nike

通常在交换函数中,我们希望看到被调用函数中交换的值。在这里,我试着看看很少的操作是如何与指针一起进行的,但我得到了错误。

我试着寻找通过引用传递的标签,但我没有找到有用的东西,所以我在这里发布我的代码。

请告诉我出现此错误的原因。

  #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函数有什么区别?
我是否错误地解释了这段代码?

图片:http://i.stack.imgur.com/CoC7s.png

最佳答案

因为你没有为指针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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com