简体   繁体   中英

qsort with pointer of pointer of struct

i have this struct:

typedef struct arvDado Arv; 
struct arvDado{
    char c;
    int qtd;
    Arv* dir;
    Arv* esq;
};

and i am making a array of pointer of this struct :

Arv** vetArv = (Arv**)malloc(sizeof(Arv*)*qtd);

i want to make a qsort but i think that my comper function is not working...

comper function:
int comparaCelula(const void *x, const void *y){
  Arv *a=(Arv*)x, *b=(Arv*)y;
  printf(" %d x %d",a->qtd,b->qtd);
  if(a->qtd == b->qtd) return 0;
  if(a->qtd < b->qtd) return -1;
  if(a->qtd > b->qtd) return 1;
}

for any case with you want to see my implementation of qsort is this:

array of point of Arv = Arv** vetCell / size of vet = qtd / size of struct Arv / comper function

qsort(vetCel, qtd, sizeof(Arv*), comparaCelula);

The compare function for qsort is given the ADDRESS of the elements in the array. Since your array is an array of pointers, you're getting pointers to pointers. So, this line:

Arv *a=(Arv*)x, *b=(Arv*)y;

should be:

Arv *a=*((Arv**)x), *b=*((Arv**)y);

since x and y are pointers to pointers to Arv (Arv**)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM