Home > Mobile >  How to swap two structures [closed]
How to swap two structures [closed]

Time:09-16

I was trying to swap the content of two array positions where the array is an array of structures. My code is:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct Student
{
    char name[800];
    int roll;
    double phys,chem,maths,sum;
};

typedef struct Student Student;

void main()
{
    Student *st,temp;
    int n,i,j;
    printf("Enter the number of students : \n");
    scanf("%d",&n);
    st = (Student *)malloc(n*sizeof(Student));
    printf("Enter the details of each student : \n");
    for(i=0;i<n;i  )
    {
        scanf(" %s %d %lf %lf %lf",&st[i].name,&st[i].roll,&st[i].phys,&st[i].chem,&st[i].maths);
        st[i].sum = st[i].phys   st[i].chem   st[i].maths;
    }
    for(i=0;i<(n-1);i  )
    {
        for(j=0;j<(n-i-1);j  )
        {
            if(st[j].sum < st[j 1].sum);
            {
                temp = st[j];
                st[j] = st[j 1];
                st[j 1] = temp;
            }
        }
    }
    printf("The list of student is : \n");
    for(i=0;i<n;i  )
    {
        printf("%d %s \n",st[i].roll,st[i].name);
    }

    getch();
}

But this swapping is not taking place. I have done this similar swapping with static structure array and it was working but this swap is not. I am not generating any error it is compiling perfectly fine. Actually, I am trying to swap it based on descending order. But the output is always just the reverse of input. Can anyone please help?

CodePudding user response:

There is a bug in your code. Inside the double for loop, after if condition, there is ;, which means your if does not guard statements inside the {} block. Remove that and it should work fine. See line 3 of the below code:

for(i=0;i<(n-1);i  ) {
    for(j=0;j<(n-i-1);j  ) {
        if(st[j].sum < st[j 1].sum) {
             temp = st[j];
             st[j] = st[j 1];
             st[j 1] = temp;
        }
    }
}
  • Related