HW_Tang
HW_Tang

Reputation: 107

How to understand type cast for pointer arrays?

I am reading 《The C Programming Language》, second edition. I am a little confused about type cast for pointer arrays. The original full code can be found at here.

char *lineptr[100];
void qsort(void *lineptr[], int left, int right, int (*comp)(void *, void *));
main()
{
    //some code are omitted

    //usage 1, original code in the book
    qsort((void **) lineptr, 0, nlines-1, (int (*)(void*,void*))(numeric ?numcmp : strcmp));

    //usage 2, my understanding
    qsort((void *) lineptr, 0, nlines-1, (int (*)(void*,void*))(numeric ?numcmp : strcmp));
}

The author said "Any pointer can be cast to void * and back again without loss of information, so we can call qsort by casting arguments to void *." (chapter 5.11)

I have tested that both usage 1 and usage 2 can run successfully. I know usage 1 should be right, but how about usage 2 ? From my opinion, usage 2 should be right for casting lineptr to void *. What's the difference between (void **) lineptr and (void *) lineptr in this instance ?

Upvotes: 0

Views: 75

Answers (1)

Lundin
Lundin

Reputation: 213989

You can't convert an array pointer void* lineptr[] to a void**, they are not compatible types. But qsort expects a pointer void* to the first element, so this isn't correct no matter.

Given char *lineptr[100];, then in C, simply pass the lineptr to qsort as-is, without casting.

Inside the callback, each void* will actually point at the address of a char*, so you might have to do something strange-looking like char* ptr = *(char**)param;.

In C++ you should be using std::sort instead.

Upvotes: 1

Related Questions