Nazeem Nazeem - 1 year ago 91
C Question

Swapping Dynamic allocated structures

I am trying to swap two structures which are dynamically allocated. But only string(name) is swapping. Anyone can tell me what's wrong with my snippet.

typedef struct
char name[20];
int num;
char ch;

void swap(student **a,student **b)
student *temp;
temp = *a;
*a = *b;
*b = temp;


void main()

student *s;
int i;
s = (student *)malloc(10 * sizeof(student));

printf("enter values: ");

scanf("%d %c %s",&s[i].num,&s[i].ch,s[i].name);


printf("%d %c %s\n",s[i].num,s[i].ch,s[i].name);



Answer Source

The function swap() gets two parameters of type student **. However, in the call swap(s+3,s+4);, you pass it two arguments of type student * -- as is the type of s. Could you compile it at all?

Anyway, what you are doing in the swap() function is replacing the content to which each pointer is pointing. That is, if you have had two pointers to students (say: p1, that is pointing to student s1, and p2, that is pointing to student s2), you could have called swap(&p1, &p2) and have them point to the other students (i.e., p1 to s2 and p2 to s1).

But in your main()'s code, you are not dealing with pointers to students. Rather, you try to replace the content of the students themselves -- which is not what swap() does at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download