-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.c
95 lines (76 loc) · 2.39 KB
/
test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <string.h>
#include "dynarray.h"
void print_array(DYN_ARRAY *arrayPtr);
int compare_intval(const void *t1, const void *t2);
int compare_name(const void *t1, const void *t2);
typedef struct node
{
char name[16];
char description[32];
int intval;
} NODE;
int main(void)
{
DYN_ARRAY array;
// initialize the array with the size of each entry
init_array(&array, sizeof(NODE));
// add some objects to the array
NODE node1 = { .name = "node1", .description = "I am node #1", .intval = 5 };
NODE node2 = { .name = "node2", .description = "I am node #2", .intval = 10 };
NODE node3 = { .name = "node3", .description = "I am node #3", .intval = 2 };
NODE node4 = { .name = "node4", .description = "I am node #4", .intval = 1 };
NODE node5 = { .name = "node5", .description = "I am node #5", .intval = 11 };
add_to_array(&array, &node1);
add_to_array(&array, &node2);
add_to_array(&array, &node3);
add_to_array(&array, &node4);
add_to_array(&array, &node5);
print_array(&array);
// use custom sort
sort_array(&array, compare_intval);
// loop through array and print the name
printf("After intval sort:\n");
print_array(&array);
// remove the first node
remove_from_array(&array, 0);
printf("After remove:\n");
print_array(&array);
// resort using alternate sort method
sort_array(&array, compare_name);
printf("After name sort:\n");
print_array(&array);
clear_array(&array);
printf("array length after clear is: %d\n", array.count);
// free the memory in the array
free_array(&array);
return 0;
}
void print_array(DYN_ARRAY *arrayPtr)
{
int i;
NODE *nodePtr;
for (i=0; i<arrayPtr->count; i++)
{
nodePtr = (NODE *)get_from_array(arrayPtr, i);
printf("Found node: %s intval: %d\n", nodePtr->name, nodePtr->intval);
}
}
// SORT BY INTVAL
int compare_intval(const void *t1, const void *t2)
{
if (((NODE *)t1)->intval < ((NODE *)t2)->intval)
{
return -1;
}
else if (((NODE *)t1)->intval > ((NODE *)t2)->intval)
{
return 1;
}
return 0;
}
// SORT BY NAME
int compare_name(const void *t1, const void *t2)
{
return strcmp(((NODE *)t1)->name,((NODE *)t2)->name);
}