You just need a temporary memory location of type int
. The easy way to get this is to declare temp
of type int
:
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp; }
What you did in the first version was to use temp
uninitialized, which is one of the numerous way a C program can be incorrect. Assigning to *temp
reads the value of temp
in order to write at the location it points to, but temp
was not set to any value in particular. Anything can happen.
In the second version, you set the value of temp
before using it, and you even set it to the address of a valid memory location to store an int
, so that makes everything work:
temp = malloc(sizeof(int));
if (temp == NULL)
return;
Although if you decide to write your function this way, it can fail, so it should be able to indicate to the caller somehow when it failed. One way to do this would be to make it return a success code instead of void
:
// returns -1 for failure, 0 for success
int swap(int *a,int *b){
int *temp;
temp = malloc(sizeof(int));
if (temp == NULL)
return -1;
*temp=*a;
*a=*b;
*b=*temp;
free(temp);
return 0;
}