user3856150
user3856150

Reputation: 1

Why wont this call by reference in C code work for swapping 2 values?

Normally in swap function we expect to see the values swapped in called function. Here i tried seeing how does little manipulation go with pointers and i got error.

I tried looking for pass by reference tags but i did not find something useful so i am posting my code here.

Please tell me the reason why i am getting this error.

  #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);  
  }  

Here I have temp as a pointer variable instead of the normal convention where we use an ordinary temp variable which I expected would work correctly, however it did not. x and y are passing their addresses to swap function.

How is it different from the swap function?
Am I interpreting this code incorrectly?

Image: https://i.sstatic.net/CoC7s.png

Upvotes: 0

Views: 64

Answers (2)

Lindus
Lindus

Reputation: 66

Your function Swap needs to be like this :

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

Upvotes: 0

Haris
Haris

Reputation: 12270

Because you did not allocate space for the pointer int *temp;

You have two options to do this the right way..

1) either use 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) Allocate using malloc()

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

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

Upvotes: 2

Related Questions