1
#define u32 uint32_t

struct edge {
 u32 v1;
 u32 v2;
};

struct edge *array = malloc((sizeof(struct edge))*Narray);

int struct_cmp_by_v1(const void *i, const void *j) {

  struct edge *a = (struct edge *)i;
  struct edge *b = (struct edge *)j;
  u32 x = a->v1;
  u32 y = b->v1;
  if(x < y)
    return -1;
  else if(x == y)
    return 0;
  else
    return 1;
  }

qsort(array, (size_t)(sizeof(array)/sizeof(struct edge)), sizeof(struct  edge), struct_cmp_by_v1);

I want to arrange an array of struct and qsort should only compare one of the fields of the struct so that the structures are ordered keeping the invariant that the v1 has its corresponding partner v2 even after being ordered by the v1, the case is that compiles with the flag -O3 well although it orders, the output is disordered in a certain way as many numbers of u32 to order there are many that are repeated and some many that very little anyway there is no order.

qsort orders but leaves it messy and at the end of the execution, I ask a function to check the order and exit:

amount of elements in the array:25056012
begins to order
finished ordering
1818004993
1343749791
1343749791 < 1818004993
index: 1 < 0

I do not understand what I can be ignoring, if anyone can give me a help I would appreciate it very much

2 Answers2

5

sizeof(array) gives size of a pointer

sort(array, 
(size_t)(sizeof(array)/sizeof(struct edge)), 
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This should be just 'Narray'
sizeof(struct  edge), 
struct_cmp_by_v1);
P0W
  • 46,614
  • 9
  • 72
  • 119
  • if I change it for Narray, qsort changes the elements v1 to the value 0, although the elments to be ordered are many there is no zero in them, that is, v1 nonzero – Ivan Pereyra Mar 25 '18 at 13:52
  • @IvanPereyra Please post a [_mcve_](https://stackoverflow.com/help/mcve) – P0W Mar 25 '18 at 14:01
  • sorry I did not answer before, I made a case for a smaller arrangement and I could have it sorted well, thanks. – Ivan Pereyra Mar 27 '18 at 00:40
  • The output of zeros was due to another problem in the code, but I already solve it and it works well – Ivan Pereyra Mar 27 '18 at 00:41
0

Some changes I made were:

return x > y ? 1 : -1; //in struct_cmp_by_v1
qsort(array, Narray, sizeof(struct edge), struct_cmp_by_v1);
  • you're making a serious mistake here. The [comparison function](http://en.cppreference.com/w/cpp/algorithm/qsort) must [return 0 for equal case](https://blogs.msdn.microsoft.com/oldnewthing/20090508-00/?p=18313), [like this](https://stackoverflow.com/a/49662110/995714) – phuclv Apr 05 '18 at 17:19
  • if (x == y) return 0; return x > y ? 1 : -1; – Ivan Pereyra Apr 06 '18 at 00:48