gpt4 book ai didi

c++ - C/C++ 程序在冒泡排序时崩溃

转载 作者:行者123 更新时间:2023-11-30 17:44:50 26 4
gpt4 key购买 nike

我有一个具有不同数据类型的结构数组,我想在结构的 float 上对数组进行排序,从最小到最大......我的程序运行良好,但是当我进行冒泡排序对结构数组进行排序时,程序崩溃或不再响应......这是我的代码:

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

using namespace std;


struct Stud{
long matrnr;
char vorname[30];
char name[30];
char datum[30];
float note;
};



void sortieren(Stud mystud[], int studentCounter) {
Stud tmp;
for (int i = 0 ; i< studentCounter; ++i) {
for (int j=0; j< studentCounter-1; ++j) {
if (mystud[j].note > mystud[j+1].note)
{
tmp = mystud[j+1];
mystud[j+1] = mystud[j];
mystud[j] = tmp;
}
}
}
}


int main(int argc, char **argv)
{


const int MAX = 30;
Stud stud;
Stud mystud[30]; // <<-- Array of "Stud" type
//memset((void*)mystud,0,sizeof(mystud) * sizeof(Stud));
int wordCounter(0);
int i(0); //thats the charCounter or index
int studentCounter(0);
char wort[MAX];
//int matrnr;
//char vorname[MAX];
//char name[MAX];
//char datum[MAX];
//float note;
....
....
....
....

最佳答案

这就是它的工作原理:

void sortieren(Stud mystud[], int studentCounter) {
Stud tmp;
for (int i = 0 ; i< studentCounter; ++i) {
for (int j=0; j< studentCounter-1; ++j) {
if (mystud[j].note > mystud[j+1].note)
{
tmp.matrnr = mystud[j+1].matrnr;
strcpy(tmp.vorname,mystud[j+1].vorname);
strcpy(tmp.name,mystud[j+1].name);
strcpy(tmp.datum , mystud[j+1].datum);
tmp.note = mystud[j+1].note;

mystud[j+1].matrnr = mystud[j].matrnr;
strcpy(mystud[j+1].vorname ,mystud[j].vorname);
strcpy(mystud[j+1].name , mystud[j].name);
strcpy(mystud[j+1].datum ,mystud[j].datum);
mystud[j+1].note = mystud[j].note;

mystud[j].matrnr = tmp.matrnr;
strcpy(mystud[j].vorname , tmp.vorname);
strcpy(mystud[j].name , tmp.name);
strcpy(mystud[j].datum , tmp.datum);
mystud[j].note = tmp.note;

}
}
}
}
..
...
...
...

sortieren(mystud , studentCounter);

关于c++ - C/C++ 程序在冒泡排序时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19823695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com