C / C ++程序在bubblesort上崩溃

时间:2013-11-06 21:59:13

标签: c++ c arrays struct

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

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

1 个答案:

答案 0 :(得分: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);