Created
July 22, 2013 07:50
-
-
Save qubbit/6052048 to your computer and use it in GitHub Desktop.
Sorting Array of Structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#define ARRAY_SZ 5 | |
typedef struct SingleChar | |
{ | |
unsigned char Character; | |
unsigned int Weight; | |
} *SingleCharPtr; | |
int CompareWeights(const void *a, const void *b) | |
{ | |
const SingleCharPtr p1 = (SingleCharPtr)a; | |
const SingleCharPtr p2 = (SingleCharPtr)b; | |
// printf("Weight1: %u\tWeight2: %u\n", p1->Weight, p2->Weight); | |
// return (p1->Weight - p2->Weight); | |
if (p1->Weight < p2->Weight) | |
return -1; | |
else if (p1->Weight > p2->Weight) | |
return 1; | |
else | |
return 0; | |
} | |
SingleCharPtr MakeChar(unsigned char c, unsigned int w) | |
{ | |
SingleCharPtr scptr = malloc(sizeof(struct SingleChar)); | |
if (!scptr) | |
{ | |
fprintf(stderr, "[Error] Out of memory\n"); | |
exit(1); | |
} | |
scptr->Character = c; | |
scptr->Weight = w; | |
return scptr; | |
} | |
int main(void) | |
{ | |
SingleCharPtr *chars = malloc(ARRAY_SZ * sizeof(SingleCharPtr)); | |
chars[0] = MakeChar('B', 3); | |
chars[1] = MakeChar('E', 7); | |
chars[2] = MakeChar('A', 4); | |
chars[3] = MakeChar('D', 6); | |
chars[4] = MakeChar('C', 2); | |
qsort(chars, ARRAY_SZ, sizeof(SingleCharPtr), &CompareWeights); | |
int i; | |
for (i = 0; i < ARRAY_SZ; i++) | |
{ | |
printf("Character: %c\tWeight: %u\n", chars[i]->Character, chars[i]->Weight); | |
free(chars[i]); | |
} | |
free(chars); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment