So there are lots of examples of using qsort()
with structures, pointers, etc. But none of them seem to sort correctly in my implementation.
This is an overview of my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int value;
};
typedef struct node Node;
int compare(const void *p1, const void *p2);
int main()
{
Node *myArray[10];
Node *node1, *node2, *node3;
int i;
node1 = (Node *)malloc(sizeof(Node));
node1->value = 10;
myArray[0] = node1;
node2 = (Node *)malloc(sizeof(Node));
node2->value = 7;
myArray[1] = node2;
node3 = (Node *)malloc(sizeof(Node));
node3->value = 12;
myArray[2] = node3;
for (i=0; i<3; i++) {
printf("Element %i: %i\n", i, myArray[i]->value);
}
printf("-------------\n");
qsort(myArray, 3, sizeof(Node*), compare);
for (i=0; i<3; i++) {
printf("Element %i: %i\n", i, myArray[i]->value);
}
return 0;
}
int compare(const void *p1, const void *p2)
{
Node *node1 = (Node*) p1;
Node *node2 = (Node*) p2;
return node1->value - node2->value;
}
This code is to demonstrate my issue, so please don't have a rant at me for semantics! The extra unused space in the array is intentional. :p
So as far as I'm aware, and from what I'm reading online, this should work. But it doesn't. For some reason it starts sorting through garbage values in the compare function.
I require the array to often be larger than the values within it, so hoped the second argument of the qsort()
function would limit it to only the first 3 elements in this case. But it seems to be ignoring that.
Any ideas what's causing this strange behaviour?