Ich versuche, meine Nummer Sortier Insertionsort Code anzupassen eine Eingabedatei von Strings zu sortieren, anstatt zB:Sortierung Strings mit Insertionsort in C - Segmentierungsfehler
thickness
combed
revocable
escorted
Jedoch habe ich einen Segmentation Fault (Kern erhalten dumped) bei dem Versuch, die unten ausgeführt wird:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 80
#define ARRAY_LEN 10000
void insertion_sort(char **a, int n) {
int i;
int j;
char *key;
for (i = 1; i < n; i++) {
key = a[i];
j = i - 1;
while (strcmp(key, a[j]) == -1 && j >= 0) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
int main(void) {
int j;
int num_words = 0;
char word[STRING_LEN];
char *wordlist[ARRAY_LEN];
while (num_words < ARRAY_LEN && 1 == scanf("%79s", word)) {
wordlist[num_words] = emalloc((strlen(word) + 1) * sizeof wordlist[0][0]);
strcpy(wordlist[num_words], word);
num_words++;
}
insertion_sort(wordlist, num_words);
for (j = 0; j < num_words; j++) {
printf("%s\n", wordlist[j]);
}
return EXIT_SUCCESS;
}
ich habe festgestellt, indem die while
Bedingung > 0
statt >= 0
while (strcmp(key, a[j]) == -1 && j > 0)
Es sortiert alles, aber die erste Saite, wie das ist, wenn j
0
ist und die Schleife nicht eingegeben, und der Ausgang ist:
thickness
combed
escorted
revocable
ich zu C neu bin und ich sammle das ist im Zusammenhang mit dem Zugriff auf Speicher, der nicht zugewiesen wurde, aber ich kämpfe um zu sehen, wo.
Sie treffen heute auf alle 8-Zylinder! –
@ DavidC.Rankin: auf etwas wichtigere Arbeit zu zaudern ist solch eine unglaublich effektive Motivation ';-)' – chqrlie
@yhsdygdyusgdysgdsudsd: Können Sie bitte diese Antwort akzeptieren, indem Sie auf das graue Häkchen unter dem Antwortpunkt klicken? – chqrlie