#include <stdio.h>
#include <stdlib.h>

typedef struct snake snake;
struct snake {
    int x; /* x coordinate */
    int y; /* y coordinate */
    snake *previous;
    snake *next;
};

snake *initSnake(void) {
    snake *pointer, *tmp1, *tmp2 = NULL;
    /* three iterations, so the snake will have a length of three */
    for( int i = 0; i<3; i++) {
        if(NULL == (tmp1 = (snake*)malloc(sizeof(snake)))) {
            return NULL;
        }
        /* coordinates */
        tmp1->x = 20;
        tmp1->y = 10 + i;
        /* first previous points to NULL */
        tmp1->previous = tmp2;
        if (tmp2)
           tmp2 -> next = tmp1; 
        /* temporarily store last pointer to be used for next previous pointer */
        tmp2 = tmp1;
        if(0 == i) {
            /* store first pointer so it can be returned */
            pointer = tmp1;
        }

    }
    /* the last next pointer has to point to NULL */
    tmp1->next = NULL;
    /* now return the pointer to the first element in list */
    return pointer;
}


int main() {
    /* pointer to first element in list */
    snake *head = NULL;

    if(NULL == (head = initSnake() ) ) {
        fprintf(stderr, "Not enough memory!\n");
        return EXIT_FAILURE;
    }
    /* here everything works fine */
    printf("%d\n", head->y);
    printf("%d\n", head->previous);
    /* when trying to acces the content of the next element, the program crashes... */
    printf("%d\n", head->next->x);
    /* pause */
    getchar();
}
