fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct snake snake;
  5. struct snake {
  6. int x; /* x coordinate */
  7. int y; /* y coordinate */
  8. snake *previous;
  9. snake *next;
  10. };
  11.  
  12. snake *initSnake(void) {
  13. snake *pointer, *tmp1, *tmp2 = NULL;
  14. /* three iterations, so the snake will have a length of three */
  15. for( int i = 0; i<3; i++) {
  16. if(NULL == (tmp1 = (snake*)malloc(sizeof(snake)))) {
  17. return NULL;
  18. }
  19. /* coordinates */
  20. tmp1->x = 20;
  21. tmp1->y = 10 + i;
  22. /* first previous points to NULL */
  23. tmp1->previous = tmp2;
  24. if (tmp2)
  25. tmp2 -> next = tmp1;
  26. /* temporarily store last pointer to be used for next previous pointer */
  27. tmp2 = tmp1;
  28. if(0 == i) {
  29. /* store first pointer so it can be returned */
  30. pointer = tmp1;
  31. }
  32.  
  33. }
  34. /* the last next pointer has to point to NULL */
  35. tmp1->next = NULL;
  36. /* now return the pointer to the first element in list */
  37. return pointer;
  38. }
  39.  
  40.  
  41. int main() {
  42. /* pointer to first element in list */
  43. snake *head = NULL;
  44.  
  45. if(NULL == (head = initSnake() ) ) {
  46. fprintf(stderr, "Not enough memory!\n");
  47. return EXIT_FAILURE;
  48. }
  49. /* here everything works fine */
  50. printf("%d\n", head->y);
  51. printf("%d\n", head->previous);
  52. /* when trying to acces the content of the next element, the program crashes... */
  53. printf("%d\n", head->next->x);
  54. /* pause */
  55. getchar();
  56. }
  57.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
10
0
20