0

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

#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;
        ....
....
....
....
4

1 回答 1

0

这就是它的工作原理:

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);
于 2013-11-06T22:27:02.647 回答