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.
void swap(student **a,student **b)
temp = *a;
*a = *b;
*b = temp;
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);
swap() gets two parameters of type
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.