ADTast-experimentalpthread-emulationqualifiedEnum
Last change
on this file since 0bd6a14 was
48b7085e,
checked in by Aaron Moss <a3moss@…>, 6 years ago
|
Start into generic types design in thesis
|
-
Property mode set to
100644
|
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.