Hey forum,
currently I am working my way through "Head First C" and I have some trouble in understanding the whole pointer / char-pointer thing.
The chapter I am currently working on deals with function pointers, and the example given is the qsort-function.
In one of the exercizes I was to write comparator functions to pass to qsort(). One of these functions is supposed to compare names. The signature should be the following:
Code:
int compare_names(const void* a, const void* b) { }
My solution was:
Code:
int compare_names(const void* a, const void* b)
{
char *name_a = (char*)a;
char *name_b = (char*)b;
return strcmp(*name_a, *name_b);
}
but the book uses pointers to pointers:
Code:
int compare_names(const void* a, const void* b)
{
char **name_a = (char**)a;
char **name_b = (char**)b;
return strcmp(*name_a, *name_b);
}
and I am not sure, why in this special case this is a difference. I'm all confused by this whole pointers stuff, but I try to give you an idea of my thoughts:
A string variable can be a char array, or it can be a pointer to char. When I pass a pointer to char to the compare_names() function, I pass a pointer to the location, where my string (or better: the first character of my string) is stored.
Since the argument is a void pointer, I have to cast it to a char pointer again to work with it.
So why do I need a pointer to a pointer here?
Any hints or help in understanding this will be appreciated.