[Solved] Casting Void Pointers in C Programming [closed]


Well the simple thing is here you would be good to go even if you didn’t use casting in these 2 statements

char** sa = (char**)a;
char** sb = (char**)b;

Because conversion from void* to char** is implicit. This would also be fine (provided you assign it to correctly qualified variable name).

const char** sa = a;

The thing is, here we need to do this (assignment) so that the address contained in a and b are considered as char** and dereferenced value of them are used in strcmp. You can also do this alternatively

return strcmp(*((const char**)sa), *((const char**)sb));

without using any extra variables.

Again more importantly, one thing to note is that – here you are violating the constraint that is there due to use of the const in the parameters. You would be good to go

const char** sa = (const char**)a;
const char** sb = (const char**)b;

The return line is basically returning the result of the comparison of two strings – which may result in -1,1 or 0 based on the compared values. This can be used as a comparator function to the standard library sorting qsort.

0

solved Casting Void Pointers in C Programming [closed]