problem with qsort and array via calloc

• 11-22-2009
Zimbobo
problem with qsort and array via calloc
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; }```
• 11-22-2009
laserlight
The problem lies here:
Code:

`size_t Circle_leng = sizeof(Circle)/sizeof(struct Point);`
This works for determining the number of elements of the array Circle when it is indeed an array of struct Point, but when it is a pointer, sizeof(Circle) gives the size in bytes of the pointer, not the array.

From what I see, you can just use m instead.
• 11-22-2009
Zimbobo
Yuhooo, you are right.