- Not quite: w1 is a pointer to a pointer to a Word. This is because your list itself contains pointers, and qsort passes the address of the element you are sorting, in this case the pointer to a Word - address of a pointer to Word -> pointer to pointer to Word.
To get back to a pointer to word, you need to dereference (use one *).
- For this to happen, w1 has to be cast into the right form and then dereferenced, so that nw1 points to w1's Word, not to the pointer w1 itself.
The form "const Word" and "Word const" are the same thing - you can put "const" on either side of the type, with the same effect. This form means that the pointer itself is a constant value, so you are not changing the pointer - this would be correct if you also put "const Word *nw1" - which would work fine for your code - you are just comparing the data inside your structure, so you CAN (should[1]) use "const Word *nw1".
Correct?
Now, just to get a bit clearer on the syntax and the use of const, I tried running a few alternatives through gcc, with the following results:
Case 1Result: Compiled without error and coincidentally or otherwise, program seemed to work.Code:Word *nw1 = *(Word **)w1;
Case 2:Result: gcc produces the following message: warning: initialization discards qualifiers from pointer target typeCode:Word *nw1 = *(Word const **)w1;
Case 3:Result: Same as Case 2Code:Word *nw1 = *(const Word **)w1;
So as a conclusion:
is the preferred code.Code:const Word *nw1 = *(const Word * const *)w1;
[1] Whilst some people would disagree, I think most would agree that WHENEVER POSSIBLE, const should be there.
In light of the above:
- Is the const in the 'correct' version (i.e. the coloured one at the top of this post) just there as a safeguard?
- Also in the 'correct' version, does const make the pointer read-only, or does it make the Word struct that it points to read-only?
- What is the difference between (Word * const *), (Word const **) and (const Word **)?
--
Mats