【问题标题】:How to swap two structures [closed]如何交换两个结构[关闭]
【发布时间】:2021-09-15 05:41:24
【问题描述】:

我试图交换两个数组位置的内容,其中数组是结构数组。 我的代码是:

#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();
}

但是这种交换并没有发生。我已经用静态结构数组完成了类似的交换,它正在工作,但这个交换不是。我没有产生任何错误,它编译得很好。实际上,我正在尝试根据降序交换它。但输出总是与输入相反。有人可以帮忙吗?

【问题讨论】:

  • 请将显示的代码简化为minimal reproducible example,这表明交换两个条目的简单尝试失败。尽量避免为此需要输入,即从代码中填充相关数据结构或使用硬编码的初始值。尝试在输出中可视化是什么让您认为交换失败。手动创建您期望的输出并将其与您获得的输出进行比较。
  • 如果您在任何地方使用 scanf 并在代码中遇到任何问题,您应该通过检查成功扫描的返回值来仔细检查扫描是否成功。
  • 无法复制。有了完全不相关的更改,我在这里tutorialspoint.com/compile_c_online.php 尝试了您的代码,它产生的输出表明输入已经排序,并且发生了明显的交换。你必须证明你所观察到的。输入是两行,以相反的顺序出现在输出中,即使输出是奇数。
  • 结构交换没问题。该错误在其他一些代码中
  • 您的确切输入是什么?你的确切输出是什么?您期望得到哪种输出?

标签: arrays c struct


【解决方案1】:

您的代码中存在错误。在双重for 循环内,在if 条件之后,有;,这意味着您的if 不会保护{} 块内的语句。 删除它,它应该可以正常工作。见下面代码的第 3 行:

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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多