0

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);
1
  • 2
    proces** procesi = malloc(sizeof(proces));--->proces** procesi = malloc(st*sizeof(proces*)); Commented May 5, 2013 at 10:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It works now, but I'm getting a warning: warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]
My bad. Fixed the example. I hardly ever use const myself, highly overrated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.