我正在尝试对结构数组进行排序,但我不知道我做错了什么......
这是我的结构:
typedef struct{
char name[15];
char score[15];
}scores;
这是我的文件:
Eric 2500
John 4000
Chris 2000
Karen 1000
Lizzie 3000
我读了文件,所以现在我的结构有了名称和分值,但是当我尝试使用同学给我的插入排序算法对其进行排序时:
void InsertionSort(scores records[RP])
{
int pos, i;
scores structInsert;
for(i=1; i<=RP; i++)
{
strcpy(structInsert.name, records[i].name);
strcpy(structInsert.score, records[i].score);
pos=i;
while(pos>0 && records[pos-1].score > structInsertar.score)
{
strcpy(structInsert.name, records[i].name);
strcpy(structInsert.score, records[i].score);
pos--;
}
if(pos!=i)
{
strcpy(records[pos].name, structInsert.name);
strcpy(records[pos].score, structInsert.score);
}
}
}
“排序”后的输出是这样的:
?2-s //Trash, Eric is gone
John 4000
Chris 2000
Karen 1000
Lizzie 3000
没有排序,请帮忙!顺便说一句,score 是一个字符,因为它用于游戏的 outtextxy()
。
最佳答案
看来您通过读取超出范围的数组导致了未定义的行为。
尝试更改i<=RP
至i<RP
以避免off-by-one error .
关于c - 如何用C语言的结构体数组实现插入排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596476/