【问题标题】:sorting an array of strings using qsort使用 qsort 对字符串数组进行排序
【发布时间】:2020-05-14 19:03:04
【问题描述】:

所以我有一个名为 nova_str[50][1024] 的字符串数组,我想要的是使用 qsort 对其进行排序,问题是它没有对任何内容进行排序。

我的输出:

* fcb
* bvb

正确的输出:

* bvb
* fcb

你可以看到数组没有被排序,我不知道为什么,所以任何帮助将不胜感激。

程序:

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


int string_cmp (const void * a, const void * b ) {
    const char * pa = *(const char * const * ) a;
    const char * pb = *(const char * const * ) b;

    return strcmp(pa,pb);
}

void print_array(char array[][1024], int len) 
{ 
    int i;
    for(i=0; i<len; i++)
    {
        printf("* %s\n",array[i]);
    }

}

int main(void)
{
    char nova_str[50][1024];
    strcpy(nova_str[0],"fcb");
    strcpy(nova_str[1],"bvb");
    qsort(nova_str,1, sizeof(char *)*1024, string_cmp);
    print_array(nova_str,2);
}

【问题讨论】:

  • 数组中有 2 个元素,但您只排序了 1 个,它应该类似于 qsort(nova_str, 2, sizeof *nova_str, string_cmp);
  • 您只对1 元素进行排序,并且将错误的元素大小传递为sizeof(char *)*1024。即1024 时间是指针 的大小。 qsort(nova_str, 2, sizeof nova_str[0], string_cmp) 会起作用。
  • qsort(nova_str, 2, 1024, strcmp); 也可以在不创建自己的比较器函数的情况下工作。
  • 您的比较函数错误,qsort(如果按照建议正确调用)将只传递您的字符串的指针,而不是指向指针的指针。
  • @WeatherVane 直接使用strcmp 会发出“指针类型不兼容”的警告(至少在gcc 上)

标签: c arrays pointers quicksort


【解决方案1】:

这会奏效。

// You are getting a pointer from qsort, not a pointer to a pointer.
int string_cmp (const void * a, const void * b ) {
    const char * pa = (const char *) a;
    const char * pb = (const char *) b;

    return strcmp(pa,pb);
}

void print_array(char array[][1024], int len) 
{ 
    int i;
    for(i=0; i<len; i++)
    {
        printf("* %s\n",array[i]);
    }

}

int main(void)
{
    char nova_str[50][1024];
    strcpy(nova_str[0],"fcb");
    strcpy(nova_str[1],"bvb");
    // the size is 2, not 1
    // you also want the correct size of the elements
    // getting the size of the first element will ensure this
    qsort(nova_str,2, sizeof(nova_str[0]), string_cmp);
    print_array(nova_str,2);
}

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2011-07-19
    • 2010-12-20
    • 2013-03-23
    • 2013-02-06
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多