Originally Posted by
cpjust
I can't see why that code is unnecessarily complicated?
Instead of:
wouldn't this be much simpler?
or to be const-correct:
Of course its easier. But only in the same sense as its easier to write
Example
Code:
int j;
for(;j < 5; j++)
{
}
Example
Code:
int j;
scanf("%d", j);
Man those sure saved me a whole lot of typing. Too bad my code is invalid. Lets use some typedefs (I know how much Elysa hates them but oh well).
Code:
typedef char **type1;
typedef char *type2;
Ok, this isn't the best type name convention, however it paints the picture I am wanting you to see. A type1 is certainly not a type2, right? In fact, a type1 is a pointer to a type2.
Code:
int compare(const void *a, const void *b)
{
// void* can be ANYTHING. But today we want the void pointer to be a type2.
type1 xptr = (type1)a;
type1 yptr = (type1)b;
// Remembering that xptr and yptr are both pointers to type2 objects we need to remember
// to compare what they point to.
type2 x = *xptr;
type2 y = *yptr;
// do whatever here.
}
I hope that helps. And to clear up one issue for Dave, its ok to do without casting when it comes to a void*, but not a void**. So int *j = malloc(5) is cool. But int **j = malloc(5) requires a cast. I hope that helps too.