c qsort string array

倾然丶 夕夏残阳落幕 提交于 2019-12-12 03:09:34

问题


    qsort(words, size1, size2, compareWords);

inside compare words:

    int compareWords(const void *ac, const void *bc)

this works:

    char const *a = *(const char **)ac;

these don't (a gets some garbage values):

    char const *a = ac;
    char const *a = (const char *) ac;

what is the rationale?

Also, in some examples I see size2 to be sizeof(char *). Shouldn't this be sizeof(*words)?

words is declared as: char *words[] = {"abc", "pqr", "abcd", "pqsl"};


回答1:


When qsorting an array of T, your comparison function must convert its const void* pointers to const T*, because T can't be taken by value.

If words is an array of char* or char const *, you have to convert the arguments to char* const * or char const * const * respectively, it's natural when said this way.



来源:https://stackoverflow.com/questions/18400333/c-qsort-string-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!