gpt4 book ai didi

对指向字符串的指针数组进行排序时崩溃

转载 作者:行者123 更新时间:2023-11-30 15:32:47 25 4
gpt4 key购买 nike

所以我搜索了这个论坛,回来后阅读了本章中有关使用 qsort() 的每一个小细节,但我似乎无法弄清楚这一点。当我运行我的代码时,它每次都会崩溃,我尝试使用我可能找到的每种不同方法进行转换,但我就是无法让它停止崩溃。

char *line[MAX_WORDS] <- This is my array I am trying to sort

qsort(line, word_count, sizeof(char*), compare_words);

int compare_words(const void *p, const void *q)
{
const char *p1 = *(char**)p;
const char *q1 = *(char**)q;
return strcmp(p1, q1);
}

这里是完整的源代码

//第 17 章编程项目 #6 //第 17 章编程项目 #5

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

#define MAX_WORD_LEN 20
#define MAX_WORDS 10

int read_line(char str[], int n);
int compare_words(const void *p, const void *q);

int main(void)
{
char *line[MAX_WORDS], word_str[MAX_WORD_LEN];
int i = 0, word_count = 0;

for (;;) {
printf("Enter word: ");
read_line(word_str, MAX_WORD_LEN);
if (strlen(word_str) == 0)
break;

line[i] = malloc(strlen(word_str));
if (line[i] == NULL) {
printf("-- No space left --\n");
break;
}

strcpy(line[i], word_str);
word_count++;
}
printf("Word_count: %d\n", word_count);
qsort(line, word_count, sizeof(char*), compare_words);

printf("\nIn sorted order:");
for (i = 0; i <= word_count - 1; i++)
printf(" %s", line[i]);
putchar('\n');

return 0;
}

int read_line(char str[], int n)
{
int ch, i = 0;

while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}

int compare_words(const void *p, const void *q)
{
const char *p1 = *(char**)p;
const char *q1 = *(char**)q;
return strcmp(p1, q1);
}

最佳答案

您超出了一些缓冲区:

line[i] = malloc(strlen(word_str));
// ...
strcpy(line[i], word_str);

您需要为终止 '\0' 字符添加空格,方法是:

line[i] = malloc(strlen(word_str) + 1);
// ...
strcpy(line[i], word_str);

line[i] = strdup(word_str);
if (line[i] == NULL) {
printf("-- No space left --\n");
break;
}

而且你在阅读单词时永远不会增加i,所以你的word_count会是5或者其他,但是所有的这些单词暂时由 line[0] 指向;其余部分(line[1]..line[4])未初始化。

将第一个 for 循环更改为:

for ( i = 0; i < MAX_WORDS; ++i ) {
// ..
}

关于对指向字符串的指针数组进行排序时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061882/

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