Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Created January 23, 2019 02:45
Show Gist options
  • Save mepcotterell/47974e51dae59d8a7ebf459aff598311 to your computer and use it in GitHub Desktop.
Save mepcotterell/47974e51dae59d8a7ebf459aff598311 to your computer and use it in GitHub Desktop.

intrusive.h

#ifndef INTRUSIVE_H
#define INTRUSIVE_H

struct list_node {
  struct list_node * next;
};

struct data_item {
  int x;
  struct list_node list1;
  struct list_node list2;  
};

#endif

intrusive.c

#include <stddef.h>
#include <stdio.h>
#include "intrusive.h"

int main() {

  struct data_item d1 = { 1, { NULL }, { NULL } };
  struct data_item d2 = { 2, { NULL }, { NULL } };
  struct data_item d3 = { 3, { NULL }, { NULL } };

  d1.list1.next = &d2.list1;
  d2.list1.next = &d3.list1;

  d1.list2.next = &d3.list2;

  printf("d1.x = %d\n", d1.x);

  // in list1
  struct list_node * next_node = d1.list1.next;
  struct data_item * next = (struct data_item *) ((char *) next_node - offsetof(struct data_item, list1));
  printf("d2.x = %d\n", next->x);
  printf("d2.x = %d\n", (*next).x);  

  next_node = next_node->next;
  next = (struct data_item *) ((char *) next_node - (char *) &((struct data_item *) 0)->list1);
  printf("d3.x = %d\n", next->x);
  printf("d3.x = %d\n", (*next).x);  
  
  return 0;

} // main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment