显然,您将alumn 结构数组与指向 alumm struct 的指针数组混淆了。
Bubble 逻辑 expexts 指针数组,主函数似乎用结构数组调用它。
由于 alumn 结构的大小,对指针执行冒泡排序可能更有效,因为每次交换将需要更少的数据移动(一个指针的 3 个副本,每个几个字节,而 alumn 的 3 个副本结构,每个 200+ 字节!)。
我建议您修改 main() 函数的逻辑(未在问题片段中显示),以引入这样一个指向实际校友结构的指针数组。(当然,这个指针数组不会让您免于分配结构本身、块(在结构数组中)或单独分配。
在你的坚持下,我在这里暗示 main 如何生成一个可供气泡使用的指针数组(气泡保持不变)。
顺便说一句,我声明校友 alumn *alumns[]
更容易显示意图使用。这与alumn **alumns
.
int main(int argc, char **argv)
{
alumn *alumns[]; // changed to array of pointers [to alumn structs]
// was pointer to alumn struct, likely to be used as an array thereof
int MaxNbOfAlumns = some_limit;
alumns = malloc(sizeof(*alumn) * MaxNbOfAlumns);
// Load the alumn records (from file or whereever)
// pseudo code:
// int i_alumns = 0; // points to the next free slot in alumns array
// for each record (in file or whereever...)
// alumms[i_alums] = malloc(sizeof(struct alumn));
// strcpy(alumms[i_alums]->lastname, whatever_data);
// strcpy(alumms[i_alums]->name, whatever_otherdata);
// alumms[i_alums]->par = some_int_data;
// alumms[i_alums]->nota = some_other_int_data;
// i_alums++;
... here goes some other code ...
bubble(alumns, totalAlumns); // alumns now being an array can be passed as is.
return 0;
}
或者,如果您希望像以前一样保留原始 alumns 变量,则可能需要的只是类似的东西,就在调用 bubble() 之前
int i;
alumn *ap_alumns[]; // new variable
ap_alumns = malloc(sizeof(*alumn) * totalAlumns);
for (i = 0; i < totalAlumns; i++)
ap_alums[i] = &alumns[i];
bubble(ap_alumns, totalAlumns);
应该强调的一件事是,无论它的起源如何,传递给 bubble() 的数组都可以正常排序,但是要使用它,您需要取消引用各个指针。
因此,对于您打算在 say 中使用的旧数组alumns[123].lastname
,您现在需要alumns[123]->lastname
(或者ap_alumns[123]->lastname
如果您使用第二个版本)。