-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.c
More file actions
91 lines (71 loc) · 1.69 KB
/
Copy pathexample.c
File metadata and controls
91 lines (71 loc) · 1.69 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
struct node {
// List components
struct node *next;
struct node *prev;
// Struct data
int value;
};
void example_list() {
int i;
struct node *list, *node, *tmp;
// Initialize the list
// Empty lists are just NULL pointers
list = NULL;
// Create 16 nodes and add them to the list
for(i = 0; i < 16; i++) {
node = calloc(1, sizeof(struct node));
node->value = i + 1;
list_append(&list, node);
}
// Iterate through the list
// Use this instead of manually iterating
list_foreach(&list, node) {
printf("%d\n", node->value);
}
// Iterate through the list to remove all nodes
// Note the safe version! You can't remove nodes using non-safe foreach.
// list_foreach_safe requires an additional temporary iterator.
list_foreach_safe(&list, node, tmp) {
list_remove(&list, node);
free(node);
}
}
void example_array() {
int i, n;
dyn_array(int) vals;
int othervals[] = {17, 18, 19, 20, 21, 22, 23, 24};
n = sizeof(othervals) / sizeof(int);
// Intinitalize array
array_init(&vals, int);
// Add 16 values
for(i = 0; i < 16; i++) {
array_append(&vals, i + 1);
}
// Manually expand array and copy values
array_reserve(&vals, vals.count + n);
memcpy(vals.data + vals.count, othervals, sizeof(int) * n);
vals.count += n;
// Print the values
for(i = 0; i < vals.count; i++) {
printf("%d\n", vals.data[i]);
}
// Clear the array
array_clear(&vals);
// Add different values
for(i = 0; i < 5; i++) {
array_append(&vals, 5 - i);
}
// Free the array
array_free(&vals);
}
int main() {
printf("List example:\n");
example_list();
printf("\n\nArray example:\n");
example_array();
return 0;
}