source:
doc/theses/aaron_moss_PhD/phd/code/void-generic.c@
4da152a
| Last change on this file since 4da152a was 48b7085e, checked in by , 7 years ago | |
|---|---|
|
|
| File size: 878 bytes | |
| Rev | Line | |
|---|---|---|
| [4075228] | 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 ); | |
| [48b7085e] | 37 | printf("%s\n", (char*)list_head(sl)); |
| [4075228] | 38 | } |
Note:
See TracBrowser
for help on using the repository browser.