-
compiler differences
I wrote a program for some research purpose ...anyway
the thing is that iam a mac user so i wrote the program using a C99 compiler that comes with mac...trying to avoid several C99 only features so as to compile in older compilers and mainly on older compilers running on windows machines.
the code did compile and it did produce an executable (using Microsoft Visual Studio 2003) but it gave wrong results after a little bit debugging i found out that what was failing was the qsort command.
here is the code... typical but i would appriciate if anyone can guess(or knows) why it fails...
Code:
int cmp(const void* a, const void* b)
{
T ai = *((T*)a), bi = *((T*)b);
if(ai<bi)
return -1;
else if(ai>bi)
return 1;
else
return 0;
}
Code:
int g;
for (g = 0; g < i; g++)
{
x[g] = real[g].Px;
y[g] = real[g].Py;
}
qsort(x, i ,sizeof(real[i].Px), &cmp);
qsort(y, i ,sizeof(real[i].Py), &cmp);
the code of course works excellent when compiled with xcode's compiler...the problem is with the window's compiler
-
Code:
#include <stdio.h>
#include <stdlib.h>
typedef double T;
int compare(const void *a, const void *b)
{
const T *x = a, *y = b;
if ( *x > *y )
{
return 1;
}
if ( *x < *y )
{
return -1;
}
return 0;
}
int main(void)
{
T t[] = {3,2,7,4,6,9,1,3,6,0};
size_t i;
for ( i = 0; i < sizeof t / sizeof *t; ++i )
{
printf("%g,", t[i]);
}
putchar('\n');
qsort(t, i, sizeof *t, compare);
for ( i = 0; i < sizeof t / sizeof *t; ++i )
{
printf("%g,", t[i]);
}
putchar('\n');
return 0;
}
/* my output
3,2,7,4,6,9,1,3,6,0,
0,1,2,3,3,4,6,6,7,9,
*/
This to me is just easier to read. Watch what you are feeding to qsort.