为什么在C代码中通过引用调用这个函数来交换2个值呢?

时间:2015-08-28 07:36:18

标签: 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作为指针变量而不是普通约定,我们使用普通的临时变量,我期望它能正常工作,但事实并非如此。 x和y将它们的地址传递给交换函数。

与交换功能有什么不同?
我是否错误地解释了这段代码?

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

2 个答案:

答案 0 :(得分:2)

因为您没有为指针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;

OR,

2)使用malloc()

分配
int *temp = malloc(sizof(int)); 

*temp=*a;   /*swapping values pointed by pointer */   
*a=*b;  
*b=*temp; 

答案 1 :(得分:0)

你的功能交换需要像这样:

    void swap(int *a, int *b)
   {
      int temp;
      temp = *b;
      *b   = *a;
      *a   = temp;   
   }