Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stddef.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct node {
- struct node *next;
- char payload[0];
- };
- static struct node *node_from_payload(void *p)
- {
- return (void *)((char *)p - offsetof(struct node, payload));
- }
- static void *list_push_(void **head, const void *data, size_t size)
- {
- struct node *n = malloc(sizeof *n + size);
- if (!n)
- return NULL;
- memcpy(n->payload, data, size);
- n->next = *head ? node_from_payload(*head) : NULL;
- *head = n->payload;
- return n->payload;
- }
- #define list_push(head, value) \
- list_push_((void **)(head), &(value), sizeof(value))
- static void *list_next_(void *p)
- {
- struct node *n = node_from_payload(p);
- return n->next ? n->next->payload : NULL;
- }
- #define list_next(p) ((typeof(p))list_next_(p))
- static void list_free(void *head)
- {
- while (head) {
- struct node *n = node_from_payload(head);
- head = n->next ? n->next->payload : NULL;
- free(n);
- }
- }
- struct point {
- int x, y;
- };
- int main(void)
- {
- int *numbers = NULL;
- int a = 1, b = 2, c = 3;
- list_push(&numbers, a);
- list_push(&numbers, b);
- list_push(&numbers, c);
- for (int *p = numbers; p; p = list_next(p))
- printf("%d\n", *p);
- struct point *points = NULL;
- struct point p1 = {1, 2};
- struct point p2 = {3, 4};
- list_push(&points, p1);
- list_push(&points, p2);
- for (struct point *p = points; p; p = list_next(p))
- printf("(%d, %d)\n", p->x, p->y);
- list_free(numbers);
- list_free(points);
- }
Advertisement
Add Comment
Please, Sign In to add comment