fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. struct linked_node
  6. {
  7. void* data;
  8. struct linked_node* next;
  9. };
  10.  
  11. struct data_x { int i; char c; };
  12. struct data_y { char* s; };
  13.  
  14. void add_node(struct linked_node** a_head, void* a_data)
  15. {
  16. struct linked_node* new_node = malloc(sizeof(*new_node));
  17. new_node->data = a_data;
  18. new_node->next = 0;
  19. if (!*a_head)
  20. {
  21. *a_head = new_node;
  22. }
  23. else
  24. {
  25. /* ... */
  26. }
  27. }
  28.  
  29. int main(void)
  30. {
  31. struct linked_node* list_x = 0;
  32. struct data_x* dx = malloc(sizeof(*dx));
  33. dx->i = 4;
  34. dx->c = 'a';
  35.  
  36. add_node(&list_x, dx);
  37.  
  38. if (list_x)
  39. {
  40. struct data_x* x = list_x->data;
  41. printf("x.i=%d x.c=%c\n", x->i, x->c);
  42. }
  43.  
  44. struct linked_node* list_y = 0;
  45. struct data_y* dy = malloc(sizeof(*dy));
  46. dy->s = "hello";
  47.  
  48. add_node(&list_y, dy);
  49.  
  50. if (list_y)
  51. {
  52. struct data_y* y = list_y->data;
  53. printf("y.s=%s\n", y->s);
  54. }
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
x.i=4 x.c=a
y.s=hello