0

i've been trying to sort 2D array with qsort like:

I want to sort it with qsort increasing or decreasing by x value, and if x values are same, i want it to compare the y values. it should be printing like this:

1, 2 - 2, 3 - 2, 4

I tried so hard, please help me.

#include <stdio.h> #include <stdlib.h> struct testt{ int start; int len; }; int comparePlease(const void* p, const void* q) { struct testt* x = (struct testt*)p; struct testt* y = (struct testt*)q; return *x - *y; } int main() { struct testt test[5] = { {40, 20}, {50, 30}, {30, 100}, {50, 35}, {25, 15} }; qsort(test, sizeof(test) / sizeof(test[0]), sizeof(int), comparePlease); } 

enter image description here

12
  • Where is the code that cals qsort? Please provide a minimal reproducible example. Commented Nov 22, 2020 at 8:04
  • i have added it @Jabberwocky Commented Nov 22, 2020 at 8:07
  • 1
    sizeof(int) -> sizeof(struct test) Commented Nov 22, 2020 at 8:08
  • 1
    @Jabberwocky or sizeof(test[0]) Commented Nov 22, 2020 at 8:13
  • @MikeCAT i added the error image on post, can u please check it? Commented Nov 22, 2020 at 8:15

1 Answer 1

0

There are many issues:

  • use struct test everywhere and not struct testt.
  • qsort(test, sizeof(test) / sizeof(test[0]), sizeof(int), comparePlease) should be qsort(test, sizeof(test) / sizeof(test[0]), sizeof(test[0]), comparePlease)
  • the struct members are x and y instead of start and len.
  • your comparePlease function was totally bogous, you cannot naively substract structs, it doesn't make any sense. What would {40,20} - {30,40} be?

You want this:

struct test { int x; int y; }; int comparePlease(const void* p, const void* q) { struct test* lhs = (struct test*)p; // left hand side struct test* rhs = (struct test*)q; // right hand side /* if x values are same */ if (lhs->x == rhs->x) { /* compare the y values */ return lhs->y < rhs->y ? -1 : lhs->y > rhs->y; } else { /* compare the x values */ return lhs->x < rhs->x ? -1 : 1; } } int main() { struct test test[5] = { {40, 20}, {50, 30}, {30, 100}, {50, 35}, {25, 15} }; qsort(test, sizeof(test) / sizeof(test[0]), sizeof(test[0]), comparePlease); } 

comparePlease is a quick and dirty fix, there is possibly room form improvement, but it should give you an idea.

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

1 Comment

Could you please be consistent in how you return values?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.