gpt4 book ai didi

c - 在 C 中对字符串/结构数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:22 25 4
gpt4 key购买 nike

我是 C 语言的新手,我需要创建一个函数来对 struct Student 数据类型的数组进行排序(在元素 Student.ime 之后按字母顺序排序)。我不太确定将指针放在哪里以便返回新数组。

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

struct Student {
int id;
char ime[20];
char prezime[20];
char brindexa[20];
struct Datum datum_rodjenja;
};

struct Student sortiraj(struct Student niz[], int vel)
{
int i, j;
struct Student tempo;
tempo = niz[0];
for(j=0 ; j<vel ; j++)
{
for(i=j ; i<vel ; i++)
{
if(strcmp(tempo.ime,niz[i].ime)>0)
{
tempo = niz[i];
}
i++;
}
niz[j] = tempo;
j++;
}
return niz;
}

数组存储在 .txt 文件中,但这不是问题所在。还有一件事,我如何调用 main() 中的函数。我想也许是这样的?

niz=sortiraj(niz, vel);

有人可以给我任何提示吗?谢谢。

最佳答案

您似乎在就地对数组进行排序,因此您根本不需要返回它。另外,使用标准库函数qsort():

int cmp(const void *ap, const void *bp)
{
const struct Student *a = ap, *b = bp;
return strcmp(a->ime, b->ime);
}

struct Student students[] = { /* whatever */ };
qsort(
students,
sizeof(students) / sizeof(studends[0]),
sizeof(students[0]),
cmp
);

另外,请使用英文函数和变量名。

关于c - 在 C 中对字符串/结构数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246134/

25 4 0
文章推荐: node.js - Nodejs : TypeError: Object # has no method 'endianness'