-6

I am reading a book called head first c and they told me a concept about casting pointers. I understand why I would do it but what I want to know is how to do it? Like what is the syntax?

int compare_names(const void* a, const void* b) 
{
    const char** sa = (const char**)a;
    const char** sb = (const char**)b;
    //why would, in the return section, we use normal pointers instead of **?
    return strcmp(*sa, *sb);
}

I get that on the left side we are using 2 asterisks because sa/sb are pointers to pointers but on the right side, I have absolutely no idea what is going on. Are we making an assignment from pointer to a pointer?

Also please explain everything about the return line.

**One final question I have is when I write the a statement like (char*)a or (int*)a am I making "a" into an integer or a char?**
Nick
  • 22
  • 5
  • Now would be a great time to go through this [list of great references on C programming](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Ajay Brahmakshatriya Jan 22 '18 at 04:17

1 Answers1

0

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.

user2736738
  • 30,591
  • 5
  • 42
  • 56