使用qsort对字符串数组进行排序

问题描述 投票:1回答:1

所以我有一个名为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);
}
c arrays pointers quicksort
1个回答
3
投票

这将起作用。

// 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);
}

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.