Reputation: 105
I have a struct in C like this:
typedef struct proces {
char ime[60];
char pid[60];
char ppid[60];
char stanje;
int stdat;
char niti[60];
char poraba[60];
} proces ;
I create about 100 of them and put them into an array
proces** procesi = malloc(sizeof(proces));
int x;
for(x=0; x<st; x++){
procesi[x] = (struct proces*)malloc(sizeof(proces));
}
Now I would like to sort them with qsort. But the qsort sorts it wrong. The function looks like this:
int compar_ppid(const void *v1, const void *v2){
const proces *p1 = (proces*)v1;
const proces *p2 = (proces*)v2;
return(strcmp(p1->ppid, p2->ppid));
}
I checked the values that the compar_ppid is comparing and they seem to be something like �#d, when they should be numbers.
I guess I'm accessing the pointer and not the value, but I cant figure out what to change to get the right values.
Qsort call:
qsort(procesi, st, sizeof(proces*), compar_name);
Upvotes: 0
Views: 389
Reputation: 5307
The array you sort contains pointers to process
, so your compare function should look like:
int compar_ppid(const void * v1, const void * v2)
{
process *const*p1 = v1, *const*p2 = v2;
return strcmp((*p1)->ppid, (*p2)->ppid);
}
and as BLUEPIXY points out the allocation of the array is not using the pointer size, but the struct size.
Upvotes: 1