【问题标题】:Qsort doesn't sort array of pointers to stringsQsort 不对指向字符串的指针数组进行排序
【发布时间】: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


【解决方案1】:

改成

int length = 0;//no need malloc
char **array = NULL;//first value is NULL

qsort(array, length, sizeof(char *), comparison);//not length-1

int ch;//type of return value of getchar is int

for(int i = 0; i < 20 &&  (ch = getchar()) != '\n'; ++i)//i : guard

const char *p1 = *(const char **)p;//qsort pass pointer to object to comparison function  
const char *q1 = *(const char **)q;//if char *, char **

【讨论】:

  • go = read_word(&amp;array,length); --> go = read_word(&amp;array, &amp;length);, i &lt; *length --> i &lt; length
  • const char *p1 = *(char * const *)p;
【解决方案2】:

你会的

keep_word = word;

以后

if(word == keep_word)

括号中的条件始终为真。

附带说明,您的程序容易出错且难以理解,因为您使用了太多指针。在 main() 中,length 应该是 int,而不是 int*,数组应该是 char*,而不是 char**。在read_word 中,a 应该是char**,而不是char***。除非必要,否则不要使用指针!

【讨论】:

  • word != keep_word,如果在 '\n' 之前有字符,则导致 keep_word 位于差异位置,然后我使用 **char 因为它是指向指针的指针,任何其他想法如何malloc 一个指针数组?只是我想到的一个:p
  • 错了。在您的代码中,word==keep_word 总是。如果您执行foo=bar,那么foo==bar 总是如此,除非您稍后更改foobar 的值。您不会更改wordkeep_word 的值,而是更改它们指向的内存中的值。至于后者,数组包含很多单词还是只有一个单词?如果它只包含一个单词,它应该是指向 char 的指针,而不是指向指针的指针。
  • 可以指定strcmp作为qsort的比较函数。
猜你喜欢
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2015-12-13
  • 2011-02-03
  • 2013-10-08
  • 2014-07-04
  • 1970-01-01
相关资源
最近更新 更多