Thread: dynamic allocation and qsort

1. dynamic allocation and qsort

Hello
I don't know why this code doesn't work. I tried everything. Can you help me, please? *puppy face*

Code:
#include <stdio.h>
#include <stdlib.h>
#define COMPARE(a, b) (((a) > (b)) - ((a) < (b)))

int compare (const void *a, const void *b)
{
float fa = *(const float*) a;
float fb = *(const float*) b;
return (fa > fb) - (fa < fb);
}

int main()
{
float *v, price;
int i=0, n=32;
v=malloc(n*sizeof(float));
while(scanf("%f",&price)!='*')
{
if(++i==n)
{
n+=32;
v=realloc(v,n*sizeof(float));
}
v[i]=price;
}
n=i;
qsort(v, 10, sizeof(float), compare);
for(i=0;i<n;i++)
printf("%f",v[i]);
free(v);
return 0;
} 2. 1. Look up what scanf actually returns.
2. Pass n rather than 10 to qsort.
3. Add some newlines in your printfs. 3. 1. I changed * in EOF
2. okay
3. okay

i did it but it still do nothing  4. Originally Posted by neko369 1. I changed * in EOF
2. okay
3. okay

i did it but it still do nothing Please repost your code so we an see the actual changes. 5. Code:
#include <stdio.h>
#include <stdlib.h>
#define COMPARE(a, b) (((a) > (b)) - ((a) < (b)))

int compare (const void *a, const void *b)
{
float fa = *(const float*) a;
float fb = *(const float*) b;
return (fa > fb) - (fa < fb);
}

int main()
{
float *v, price;
int i=0, n=32;
v=malloc(n*sizeof(float));
while(scanf("%f",&price)!=EOF)
{
if(++i==n)
{
n+=32;
v=realloc(v,n*sizeof(float));
}
v[i]=price;
}
n=i;
qsort(v, n, sizeof(float), compare);
for(i=0;i<n;i++)
printf("%f\n",v[i]);
free(v);
return 0;
} 6. You're not storing the price where it should be stored (because you're incrementing 'i' before using it as the index for the array) 7. scanf() should be tested against 0, not EOF.

Don't increment i until AFTER:
Code:
v[i]=price;
i++;
In addition, please tell the user how to use the program, and how to end the input. Keyboard input or redirection from a file? Popular pages Recent additions Tags for this Thread

#include, const, float, int, void 