Guest User

Untitled

a guest
Sep 3rd, 2026
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. struct node {
  7. struct node *next;
  8. char payload[0];
  9. };
  10.  
  11. static struct node *node_from_payload(void *p)
  12. {
  13. return (void *)((char *)p - offsetof(struct node, payload));
  14. }
  15.  
  16. static void *list_push_(void **head, const void *data, size_t size)
  17. {
  18. struct node *n = malloc(sizeof *n + size);
  19. if (!n)
  20. return NULL;
  21.  
  22. memcpy(n->payload, data, size);
  23. n->next = *head ? node_from_payload(*head) : NULL;
  24. *head = n->payload;
  25. return n->payload;
  26. }
  27.  
  28. #define list_push(head, value) \
  29. list_push_((void **)(head), &(value), sizeof(value))
  30.  
  31. static void *list_next_(void *p)
  32. {
  33. struct node *n = node_from_payload(p);
  34. return n->next ? n->next->payload : NULL;
  35. }
  36.  
  37. #define list_next(p) ((typeof(p))list_next_(p))
  38.  
  39. static void list_free(void *head)
  40. {
  41. while (head) {
  42. struct node *n = node_from_payload(head);
  43. head = n->next ? n->next->payload : NULL;
  44. free(n);
  45. }
  46. }
  47.  
  48. struct point {
  49. int x, y;
  50. };
  51.  
  52. int main(void)
  53. {
  54. int *numbers = NULL;
  55. int a = 1, b = 2, c = 3;
  56.  
  57. list_push(&numbers, a);
  58. list_push(&numbers, b);
  59. list_push(&numbers, c);
  60.  
  61. for (int *p = numbers; p; p = list_next(p))
  62. printf("%d\n", *p);
  63.  
  64. struct point *points = NULL;
  65. struct point p1 = {1, 2};
  66. struct point p2 = {3, 4};
  67.  
  68. list_push(&points, p1);
  69. list_push(&points, p2);
  70.  
  71. for (struct point *p = points; p; p = list_next(p))
  72. printf("(%d, %d)\n", p->x, p->y);
  73.  
  74. list_free(numbers);
  75. list_free(points);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment