ADT
aaron-thesis
arm-eh
ast-experimental
cleanup-dtors
deferred_resn
enum
forall-pointer-decay
jacob/cs343-translation
jenkins-sandbox
new-ast
new-ast-unique-expr
no_list
persistent-indexer
pthread-emulation
qualifiedEnum
Last change
on this file since 4075228 was 4075228, checked in by Aaron Moss <a3moss@…>, 7 years ago |
Start generics chapter of thesis, add code examples of C polymorphic types
|
-
Property mode
set to
100644
|
File size:
879 bytes
|
Line | |
---|
1 | #include <stdlib.h>
|
---|
2 | #include <stdio.h>
|
---|
3 | #include <string.h>
|
---|
4 |
|
---|
5 | // single code implementation
|
---|
6 |
|
---|
7 | struct list { void* value; struct list* next; };
|
---|
8 |
|
---|
9 | // internal memory management requires helper functions
|
---|
10 |
|
---|
11 | void list_insert( struct list** ls, void* x, void* (*copy)(void*) ) {
|
---|
12 | struct list* node = malloc(sizeof(struct list));
|
---|
13 | node->value = copy(x); node->next = *ls;
|
---|
14 | *ls = node;
|
---|
15 | }
|
---|
16 |
|
---|
17 | void* list_head( const struct list* ls ) { return ls->value; }
|
---|
18 |
|
---|
19 | // helpers duplicated per type
|
---|
20 |
|
---|
21 | void* int_copy(void* x) {
|
---|
22 | int* n = malloc(sizeof(int));
|
---|
23 | *n = *(int*)x;
|
---|
24 | return n;
|
---|
25 | }
|
---|
26 |
|
---|
27 | void* string_copy(void* x) { return strdup((const char*)x); }
|
---|
28 |
|
---|
29 | int main() {
|
---|
30 | struct list* il = NULL;
|
---|
31 | int i = 42;
|
---|
32 | list_insert( &il, &i, int_copy );
|
---|
33 | printf("%d\n", *(int*)list_head(il)); // unsafe type cast
|
---|
34 |
|
---|
35 | struct list* sl = NULL;
|
---|
36 | list_insert( &sl, "hello", string_copy );
|
---|
37 | printf("%s\n", (char*)list_head(sl) );
|
---|
38 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.