PDA

View Full Version : [C] qsort di array di puntatori a strutture


qwerty86
28-08-2011, 12:43
Salve ragazzi questa cosa mi sta mandando fuori di testa.

Vi allego i codici

Questo è il file : interval.h
typedef struct _interval{

int s;
int f;
int len;
}Interval;

file interval.c


#include "interval.h"

Interval **readInterval(int n)
{
Interval **s = (Interval *) malloc(n*sizeof(Interval *));
int j;

for(j=0;j<n;j++)
{
Interval *i = (Interval *) malloc(sizeof(Interval));

scanf("%d %d",&i->s,&i->f);
i->len = i->f-i->s;

s[j]= i;
}

return s;
}

void writeInterval(Interval **s,int n)
{
int i;

for(i=0;i<n;i++)
{
printf("%d %d %d \n",s[i]->s,s[i]->f,s[i]->len);
}
}

file : testis.c

#include "interval.h"
#include <stdio.h>
#include <stdlib.h>

int cmp(const void *,const void *);

int main()
{
int n;
Interval **s;

scanf("%d",&n);
s = readInterval(n);

writeInterval(s,n);

qsort(s,n,sizeof(Interval *),cmp);
printf("******\n");
writeInterval(s,n);

}

int cmp(const void *a,const void *b)
{
const Interval *i = (const Interval *)a;
const Interval *j = (const Interval *)b;

return j->len - i->len;
}

file input.txt
5 1 4 2 4 4 5 3 4 1 2

output

1 4 3
2 4 2
4 5 1
3 4 1
1 2 1
******
3 4 1
4 5 1
2 4 2
1 4 3
1 2 1

come vede l'ordinamento non è completo.....cos'è che non va?!

AnonimoVeneziano
30-08-2011, 16:13
Non posso provare purtroppo , ma potrebbe essere che forse devi cambiare :


qsort(s,n,sizeof(Interval *),cmp);


con


qsort(*s,n,sizeof(Interval),cmp);


Ciao

qwerty86
30-08-2011, 16:31
Non posso provare purtroppo , ma potrebbe essere che forse devi cambiare :


qsort(s,n,sizeof(Interval *),cmp);


con


qsort(*s,n,sizeof(Interval),cmp);


Ciao

Grazie per l'interesse ma ho risolto.

int cmp(const void *a,const void *b)
{
const Interval *i = *(const Interval **)a;
const Interval *j = *(const Interval **)b;

return j->len - i->len;
}

In rosso è quello che andava aggiunto.

AnonimoVeneziano
30-08-2011, 16:35
Inoltre non credo tu abbia veramente la necessità di utilizzare i doppi puntatori per fare quello che fai, è sufficiente un array normale di elementi (Interval) :)

AnonimoVeneziano
30-08-2011, 16:38
Grazie per l'interesse ma ho risolto.

int cmp(const void *a,const void *b)
{
const Interval *i = *(const Interval **)a;
const Interval *j = *(const Interval **)b;

return j->len - i->len;
}

In rosso è quello che andava aggiunto.

Beh si anche così va bene, in sostanza il problema è che ordinavi sulla cosa sbagliata visto che ti mancava un livello di dereferenziamento.