Skip to content

Instantly share code, notes, and snippets.

@apfohl
Created November 26, 2015 18:31
Show Gist options
  • Save apfohl/b7ba36fe3c15db1ce05d to your computer and use it in GitHub Desktop.
Save apfohl/b7ba36fe3c15db1ce05d to your computer and use it in GitHub Desktop.
Pointer Pointer Pointer
#include <stdlib.h>
#include <stdio.h>
#include <gc/gc.h>
struct node {
int i;
};
struct node *new_node(int i)
{
struct node *node = GC_malloc(sizeof(struct node));
node->i = i;
return node;
}
void print_nodes(struct node **nodes, int n)
{
fprintf(stderr, "[");
if (n > 0) {
fprintf(stderr, "%d", nodes[0]->i);
for (int i = 1; i < n; i++) {
fprintf(stderr, ", %d", nodes[i]->i);
}
}
fprintf(stderr, "]\n");
}
int main(void)
{
GC_init();
struct node **nodes = GC_malloc(3 * sizeof(struct node *));
nodes[0] = new_node(1);
nodes[1] = new_node(2);
nodes[2] = new_node(3);
print_nodes(nodes, 3);
struct node **a = nodes + 0;
struct node **b = nodes + 1;
struct node **c = nodes + 2;
printf("a: %d\n", (*a)->i);
printf("b: %d\n", (*b)->i);
printf("c: %d\n", (*c)->i);
nodes[0] = new_node(4);
nodes[1] = new_node(5);
nodes[2] = new_node(6);
print_nodes(nodes, 3);
printf("a: %d\n", (*a)->i);
printf("b: %d\n", (*b)->i);
printf("c: %d\n", (*c)->i);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment