0

Okay, I got this to work by looking around online and such, but can someone explain what lines numbered 1 and 2 do exactly and why they are needed

int structCompare(const void *a, const void *b)
{
     struct trade *tempA = (struct trade *)a;//(1)
     struct trade *tempB = (struct trade *)b;//(2)
     return strcmp(tempA->name, tempB->name);
}

1 Answer 1

3

Those lines cast the generic void pointers to struct trade pointers. The explicit cast is superfluous in C when void * is involved and should be eliminated:

 struct trade *tempA = a;
 struct trade *tempB = b;
 return strcmp(tempA->name, tempB->name);

You could have written:

return strcmp(((struct trade *)a)->name, ((struct trade *)b)->name);

I prefer the first one though.

Sign up to request clarification or add additional context in comments.

1 Comment

Ohh, thank you. Seeing them not casted makes more sense. Also, thanks for the simplified version. Actually I have multiple layers of sorting in case the name field is the same, but I'll keep your one line solution in mind!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.