Domanda

Il programma sta leggendo la riga per riga da un file e archiviando informazioni in una struttura. Tutto funziona tranne per l'ordinamento della matrice di strutture. Ad esempio, alla fine quando sto stampando la struttura (codice incluso alla fine), funziona completamente bene.

Il problema (errore di segmentazione) si verifica quando chiamo QSORT.

Inoltre, la stampa degli studenti [0] .LastName funziona bene, ma la stampa degli studenti [1] .LastName restituisce un (null), anche questo è confuso.

Ho guardato ovunque e il mio codice sembra molto simile a quello che è stato pubblicato come soluzioni corrette per ordinare le strutture, quindi sono molto confuso.

Definizione della struttura in intestazione del principale:

// DEFINE STRUCT
typedef struct _StudentInformation  {
    int term;
    int studentId;
    char *lastName;
    char *firstName;
    char *subject;
    int catalogNumber;
    char *section;
} StudentInformation;

Allocazione della struttura nel metodo principale (Student_data = 50):

// ALLOCATE AN ARRAY OF STUDENTS (STRUCT)
    StudentInformation *students;
    if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL) {
        scanf("Error can't allocate enough students!\n");
        exit(1);
}

Il problema: chiamare QuickSort (il motivo dell'8 è perché ci sono 8 voci che funzionano e sono caricate, anche meno di 8 non funziona).:

qsort(students, 8, sizeof(StudentInformation), comparator);

Comparatore per QuickSort:

int comparator (const void * a, const void * b) {
    StudentInformation *s1 = (StudentInformation*)a;
    StudentInformation *s2 = (StudentInformation*)b;

    return strcmp(s1->lastName, s2->lastName);
}

Il motivo per cui so che i dati sono carichi sono perché la stampa funziona completamente bene:

void printInformation (StudentInformation *students) {
    // PRINT EVERYTHING
        while(students->firstName!=NULL) {
            printf("%-s, %s %15d %4d %4s%d %7s\n",
                    students->lastName,students->firstName,students->term,
                    students->studentId, students->subject,students->catalogNumber,
                    students->section);

            // Increment
            students=students+sizeof(StudentInformation);
        }
}

Ciò che stampe (ho incluso solo 2 su 8 stampato, senza null stampato):

Castille, Michael Jr            1201 103993269  CSE230     R03
Boatswain, Michael R.            1201 105515018  CSE230     R01

Grazie!

È stato utile?

Soluzione

Fornito Student_Data> = 8, c'è solo una possibile spiegazione, che è quella o più del tuo lastName I campi non sono mai stati inizializzati e contengono null o immondizia. Se il tuo loop inizializza questi campi conteneva lo stesso errore del tuo loop stampandolo (usando students=students+sizeof(StudentInformation) invece di students++), sarebbe questo il motivo.

Altri suggerimenti

La linea:

if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL)

Assegna la memoria per la struttura stessa, ma non per le stringhe a cui si fa riferimento da puntatori:

char *lastName;
char *firstName;
char *subject;
char *section;

Ognuno di questi occupa abbastanza memoria per un puntatore. Dovrai allocare la memoria per le corde separatamente:

if ((lastName = malloc((LAST_NAME_LEN + 1) * sizeof(char))) == NULL) {
  // Error
}
if ((firstName = ...

Scrivere in memoria che non possiedi è sempre un buon modo per ottenere una lezione inaspettata nel debug di un rimbalzo degli errori: probabilmente otterrai un segfault o una corruzione della memoria alla fine, ma potrebbe essere in un'area di codice che sembra esserlo Totalmente non correlato alla fonte effettiva del problema.

Tu hai detto Calling quicksort (the reason for the 8 is because there are 8 entries.

Questo non è corretto. Dovresti passare il numero di elementi nell'array (STUDENT_DATA nel tuo caso).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top