char **和char [] []之间的区别

时间:2016-08-02 00:00:44

标签: c

我正在尝试使用stdlib qsort对字符串进行排序。我创建了两个排序函数sort1和sort2。 sort1输入参数是char **,sort2输入参数是char [] []。当使用sort1函数对字符串数组进行排序时,我的程序崩溃了。

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


int compare(const void* a, const void* b)
{
    const char *ia = (const char *)a;
    const char *ib = (const char *)b;
    return strcmp(ia, ib);
}

//program crashes
void sort1(char **A, int n1) {

    int size1 = sizeof(A[0]);
    int s2 = n1;
    qsort(A,s2,size1,compare);
}

//works perfectly
void sort2(char A[][10], int n1) {

    int size1 = sizeof(A[0]);
    int s2 = n1;
    qsort(A,s2,10,compare);

}

int _tmain(int argc, _TCHAR* argv[])
{

     char *names_ptr[5] = {"norma","daniel","carla","bob","adelle"};
     char names[5][10] = {"norma","daniel","carla","bob","adelle"};
     int size1 = sizeof(names[0]);
     int s2 = (sizeof(names)/size1);    
     sort1(names_ptr,5); //doesnt work
     sort2(names,5); //works
     return 0;
}

1 个答案:

答案 0 :(得分:2)

qsort函数接收指向正在排序的事物的指针。在sort2中,您要排序 10个字符的数组。在sort1中,您正在排序指向char 的指针。

因此compare sort1函数错误,因为参数是指向char 指针的指针(转换为void *),但你转换为指向char的指针

sort2有效,因为将指针转换为10 char 的数组转换为指向char 的指针(通过void *)会生成一个指针指向那10个人的第一个角色。

您需要为这两种情况中的每种情况使用不同的比较函数,因为您要对不同的东西进行排序。