fork download
  1. #include <stdio.h>
  2. #include <stddef.h>
  3.  
  4. // Упрощённая версия одноимённого макроса из ядра Linux. :)
  5. #define container_of(ptr, type, member) ((type *)((char *)ptr - offsetof(type, member)))
  6.  
  7. typedef struct stack_node
  8. {
  9. struct stack_node* next;
  10. } stack_node;
  11.  
  12. typedef struct
  13. {
  14. stack_node* top;
  15. } stack;
  16.  
  17. void push(stack* stk, stack_node* item)
  18. {
  19. item->next = stk->top;
  20. stk->top = item;
  21. }
  22.  
  23. stack_node* pop(stack* stk)
  24. {
  25. stack_node* item = stk->top;
  26. if (item) stk->top = item->next;
  27. return item;
  28. }
  29.  
  30. typedef struct
  31. {
  32. char* name;
  33. stack_node sn;
  34. } my_object;
  35.  
  36. my_object* my_object_from_sn(stack_node* sn_ptr)
  37. {
  38. return container_of(sn_ptr, my_object, sn);
  39. }
  40.  
  41. int main(void) {
  42. my_object a = {"A"}, b = {"B"}, c = {"C"};
  43. stack stk = {};
  44. push(&stk, &a.sn);
  45. push(&stk, &b.sn);
  46. push(&stk, &c.sn);
  47.  
  48. stack_node* popped;
  49. while ((popped = pop(&stk)))
  50. printf("Popped %s.\n", my_object_from_sn(popped)->name);
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Popped C.
Popped B.
Popped A.