gpt4 book ai didi

c - 选择排序指针字符数组的段错误(核心转储)错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:32 26 4
gpt4 key购买 nike

<分区>

当我编译并运行这种选择类型的随机字符数组时,我得到了一个段错误(核心转储)错误。我认为这与在我的选择排序部分访问未分配的内存有关。有人可以帮忙吗?

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

#define STRING_LEN 80
#define ARRAY_LEN 10000

void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}

void selection_sort(char *words[], int n) {
char *temp;
int i, j;

for (i = 0; i < n; i++) {
for (j = i+1; i < n; j++) {
if (strcmp(words[i], words[j]) < 0) {
temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
}

int main(void) {
char word[STRING_LEN];
char *wordlist[ARRAY_LEN];
int num_words;
int i;

num_words = 0;
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++;
}

selection_sort(wordlist, num_words);

for (i = 0; i < num_words; i++) {
printf("%s\n", wordlist[i]);
}

for (i = 0; i < num_words; i++) {
free(wordlist[i]);
}

return EXIT_SUCCESS;
}

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