【发布时间】:2016-05-19 20:29:24
【问题描述】:
在这个 C 程序中,我将用键盘输入的单词读入一个 char 指针。指针存储在指针数组中。然后我想通过函数比较用 qsort 对数组进行排序。我给它指向我的指针数组的指针。 它根本不对数组进行排序。我不知道我是否在这里获得了 UB,或者我因分配错误而错过了内存。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool read_word(char ***a, int *length);
int comparison(const void *p, const void *q);
int main()
{
int *length = malloc(sizeof(int));
*length = 0;
char **array = malloc(sizeof(char *));
bool go = false;
while(go == false)
{
printf("Enter word: ");
go = read_word(&array,length);
}
qsort(array, *length - 1,sizeof(char *), comparison);
printf("\n");
for(int i = 0; i < *length; i++)
printf("%s\n", array[i]);
return 0;
}
bool read_word(char ***a, int *length)
{
char ch;
++*length;
char *word = malloc(20 * sizeof(char) + 1);
char *keep_word;
char **temp = realloc(*a,*length * sizeof(*a));
if(!temp)
exit(EXIT_FAILURE);
*a = temp;
keep_word = word;
while((ch = getchar()) != '\n')
*keep_word++ = ch;
*keep_word = '\0';
if(word == keep_word)
{
free(word);
--*length;
return true;
}
(*a)[*length - 1] = word;
printf("%s", (*a)[*length -1]);
printf("\nh\n");
return false;
}
int comparison(const void *p, const void *q)
{
const char *p1 = p;
const char *q1 = q;
return strcmp(p1,q1);
}
【问题讨论】:
-
请标记你的语言,我不够熟练,无法确定是C还是C++,所以我不会为你做..
-
已标记。我在这里使用 C。
标签: c arrays string pointers qsort