I have simplified my question to this small C program. Please note that I am learning C on my own. I a having real trouble with pointers!
#include <stdio.h>
#include <stdlib.h>
typedef struct Elmt_ {
int *i;
struct Elmt_ *next;
} E;
void swap_1(E *x, E *y) {
int *temp = NULL;
temp = x->i;
x->i = y->i;
y->i = temp;
}
void swap_2(E *x, E *y) {
int *temp=NULL;
temp = malloc(sizeof(int));
*temp = *(x->i);
*(x->i) = *(y->i);
*(y->i) = *temp;
}
int main() {
E *p, *q, *r, *s;
int a, b;
a = 8;
b = 50;
p = malloc(sizeof(E));
q = malloc(sizeof(E));
p->i = &a;
p->next = NULL;
q->i = &b;
q->next = NULL;
printf("Initially, *(p->i)=%d *(q->i)=%d\n", *(p->i), *(q->i));
swap_1(p,q);
printf("After swap_1, *(p->i)=%d *(q->i)=%d\n", *(p->i), *(q->i));
r = malloc(sizeof(E));
s = malloc(sizeof(E));
r->i = &a;
s->i = &b;
printf("Initially, *(r->i)=%d *(s->i)=%d\n", *(r->i), *(s->i));
swap_2(r,s);
printf("After swap_2, *(r->i)=%d *(s->i)=%d\n", *(r->i), *(s->i));
return 0;
}
**Question:**In the above program, is swap_1 or the swap_2 the right way to swap the integer value pointed to by i ?
I see that both these functions seem to swap the values given as arguments correctly.
$ ./a.out
Initially, *(p->i)=8 *(q->i)=50
After swap_1, *(p->i)=50 *(q->i)=8
Initially, *(r->i)=8 *(s->i)=50
After swap_2, *(r->i)=50 *(s->i)=8
Function
swap_1swaps the pointer values, not the pointed values.Function
swap_2swaps the pointed values, but yields a memory leak.In order to swap the pointed values cleanly, you can simply do: