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

标签 c pointers function-pointers pass-by-reference

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

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

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

  #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/

相关文章:

C 指向指针分配的指针

C++ char数组指针混淆

c - 在代码运行期间,初始化的指针是否可能为 NULL?

c++ - 参数接收的对象上的函数指针

c++ - 函数指针语法

c++ - 计算密集型C/C++程序的典型性能瓶颈是什么

c - 警告 : assignment from incompatible pointer type [enabled by default]

c - 我如何像 "top"命令那样获取每个 CPU 的统计信息(系统、空闲、良好...)?

c - 理解 C 中的信号量

C:代码重复示例