source: doc/theses/aaron_moss_PhD/phd/code/void-generic.c @ 503c350

Last change on this file since 503c350 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
Line 
1#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4
5// single code implementation
6
7struct list { void* value; struct list* next; };
8
9// internal memory management requires helper functions
10
11void 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
17void* list_head( const struct list* ls ) { return ls->value; }
18
19// helpers duplicated per type
20
21void* int_copy(void* x) {
22        int* n = malloc(sizeof(int));
23        *n = *(int*)x;
24        return n;
25}
26
27void* string_copy(void* x) { return strdup((const char*)x); }
28
29int 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.