Nazeem Nazeem - 13 days ago 5
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;
}student;

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: ");

for(i=0;i<10;i++)
scanf("%d %c %s",&s[i].num,&s[i].ch,s[i].name);

swap(s+3,s+4);

printf("\n");
for(i=0;i<10;i++)
printf("%d %c %s\n",s[i].num,s[i].ch,s[i].name);


printf("\n");
}


'

Answer

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.

Comments