Hello there,
I am having the following problem.
I am making an array of structures.
The struct contains an int.
I give this struct array to qsort to sort the struct array according to this int.
This works if I create the struct array like
struct Point track[] = { {5}, {4}, {3} };
for example.
However, I need to have a variable array size and therefore I want to use calloc.
But if I create the struct array via calloc, qsort won't sort anymore.
See bellow for the code that reproduces my problem.
If I use the calloc part instead, qsort won't sort.
Any ideas what's going on?
Thanks.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int Point_cmp(const void *a, const void *b)
{
struct Point *ia = (struct Point *)a;
struct Point *ib = (struct Point *)b;
return ia->x - ib->x;
}
main() {
size_t m = 4;
struct Point Circle[] = { {4}, {1}, {0}, {-1} };
//struct Point * Circle = NULL;
//Circle = (struct Point *) calloc( m, sizeof(struct Point));
size_t i;
for ( i = 0; i < m; i++ ) {
Circle[i].x = 100 - i;
}
for ( i = 0; i < m; i++ ) {
printf("%d ",Circle[i].x);
}
printf("\n");
size_t Circle_leng = sizeof(Circle)/sizeof(struct Point);
qsort(Circle, Circle_leng, sizeof(struct Point), Point_cmp);
for ( i = 0; i < m; i++ ) {
printf("%d ",Circle[i].x);
}
printf("\n");
return 0;
}