I'm writing a small code to test qsort on an array that is not completely filled.
But whenever I run it, the data is completely erased for some random int.
I don't understand why, I looked at this question and their code ran fine but I don't get why mine won't.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct proc {
long unsigned int user_time;
long unsigned int system_time;
char *name;
int pid;
};
static int compare(const void * a, const void * b)
{
const struct proc *p1 = a;
const struct proc *p2 = b;
if ((p1->system_time + p1->user_time) > (p2->user_time + p2->system_time))
return -1;
else if ((p1->system_time + p1->user_time) == (p2->user_time + p2->system_time))
return 0;
else
return 1;
}
int main()
{
int used_size = 0;
srand ( time(NULL) );
struct proc **processes = malloc(sizeof(struct proc*) * 20 + 1);
for (int i = 0; i < 20; i++) {
processes[i] = malloc(sizeof(struct proc));
processes[i]->user_time = 0;
processes[i]->system_time = 0;
processes[i]->name = NULL;
processes[i]->pid = -1;
}
for (int i = 0; i < 14; i++)
{
processes[i]->user_time = rand()%10;
processes[i]->system_time = 0;
processes[i]->pid = i*2;
used_size++;
}
for (int i = 0; i < used_size;i++)
{
printf("%d %lu \n",i,processes[i]->user_time);
}
printf("\n\n\n");
qsort(processes, used_size, sizeof(struct proc *), compare);
for (int i = 0; i < used_size;i++)
{
printf("%d %d \n",i,processes[i]);
}
}
compare(a, b)and returns a negative number, it must return a positive number when called ascompare(b, a)— your does not. This is a basic requirement of all compare functions forqsort(). Additionally, your function is for comparing structures via pointers to structures (when sorting an array of structures). You're actually sorting an array of pointers to structures; you need a different function that expects to be passed a pointer to a pointer.!can only return 1 or 0... and the arguments would be pointers to the elements in the array that are being compared, which themselves are pointers to the structs (in your setup)... so they should be pointers to pointers, though you treat them as though they point to the structs directly.