如何解决将 'char (*)[64]' 传递给 'const char **' 类型的参数时指针类型不兼容的问题

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

当我在

incompatible pointer types passing 'char (*)[64]' to parameter of type 'const char **'
函数中传递
name[100][64]
并最终得到
sort
 时,我一直得到 
segmentation fault 11

#define size 100
#define type 10
// Defining comparator function as per the requirement
static int myCompare(const void* a, const void* b){
    return strcmp(*(const char**)a, *(const char**)b);
}
void sort(int n, const char* arr){
    qsort(arr, n, sizeof(const char*), myCompare);
}
int main(){
    int num; scanf("%d", &num);
    char name[100][64];
    //input
    for(int i = 0; i < num; i++){
        scanf("%s", name[i]);
    }
    //sort
    sort(num, &name[0]);
}

我已尝试

char* name[100];
解决问题,但仍然收到警告 -
segmentation fault 11 

char* name[100];
//input
for(int i = 0; i < num; i++){
   scanf("%s", name[i]);
}
sort(num, name);

我想知道如何输入多个字符串并像字典一样对它们进行排序。

c string pointers qsort
1个回答
1
投票

您声明了一个字符数组,例如

char name[100][64];

在函数参数等表达式中使用时,它会隐式转换为指向

char ( * )[64]
类型的第一个元素的指针。

但是,使用数组作为参数的函数

sort
具有相应参数
const char **
的类型。

void sort(int n, const char* arr){

指针类型之间没有隐式转换。而且,即使使用隐式转换,调用也会不正确。

您的函数可以如下所示,如下面的演示程序所示。

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

#define size 100
#define type 10

static int myCompare( const void *a, const void *b ) {
    return strcmp( *( const char ( * )[type] )a, *( const char ( * )[type] )b );
}
void sort( char ( *arr )[type], size_t n  ) {
    qsort( arr, n, sizeof( *arr ), myCompare );
}

int main( void )
{
    char name[size][type] =
    {
        "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"
    };

    size_t num = 10;

    sort( name, num );

    for (size_t i = 0; i < num; i++)
    {
        printf( "%s ", name[i] );
    }

    putchar( '\n' );
}

程序输出为

0 1 2 3 4 5 6 7 8 9
© www.soinside.com 2019 - 2024. All rights reserved.