在函数

时间:2015-11-09 19:59:45

标签: c arrays struct temp

所以我有这一系列结构,其中包含竞赛中竞争对手的数据。这就是结构的设置方式:

struct competitor {
        int compID;
        char name[30];
        int swimSecs;
        int cyclSecs;
        int runSecs;
        int totalSecs;
    };

我使用这个排序数组按顺序从最小到最大排列竞争对手。 compNum是竞争对手的数量

void sort(struct competitor** a) {

    int n = compNum;


    struct competitor temp;
    int i, j;

    for (i = 1; i < n; i++)
        for (j = 0; j < n - i; j++) {



            if (a[j]->totalSecs > a[j + 1]->totalSecs) {


                temp = *a[j];

                a[j] = a[j + 1];

                *a[j + 1] = temp;

            }
        }


    return;
}

但似乎在使用temp和交换结构时,它似乎复制了一些用户输入的结构并覆盖了现有的struct数据。任何人都可以看到为什么会发生这种情况,你会如何解决它?提前谢谢

1 个答案:

答案 0 :(得分:1)

你应该交换结构,这使代码成为:

temp = *a[j];
*a[j] = *a[j + 1];   // copy the structure
*a[j + 1] = temp;

或者,更优选的是效率,只需交换指针:

struct competitor *temp;
...

temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;

代码目前正在做两件事,这是行不通的。

相关问题