-1

I was just experimenting with C and i tried to put a list inside a list. The problem is that while it prints the array->count it shows a segmentation fault when i try to change the array->head->x. What i am doing wrong? I havent finished my programm yet so thats why i use a macro.

  #include <stdio.h>
  #include <stdlib.h>
  #define N 3

  typedef struct smallList{
      int x;
      struct smallList *next;
  } smallList;

  typedef struct bigList{
      int count;
      struct bigList *next;
      smallList *head;
  } bigList;

  void main(void)
  {
      bigList *array = (bigList*)malloc(sizeof(bigList));

      array->count = 3;
      printf("%d \n", array->count);

      array->head->x = 10;
      printf("%d \n", array->head->x);
  }
wallyk
  • 56,922
  • 16
  • 83
  • 148
user5552189
  • 31
  • 1
  • 5

2 Answers2

2

You haven't allocated memory for the head variable in the array. After you malloc space for array try something like

array->head = malloc(sizeof(smallList));
Taelsin
  • 1,030
  • 12
  • 24
  • Aahhhh of course......silly me. I used array->head = (smallList*)malloc(sizeof(smallList)); – user5552189 Dec 02 '15 at 17:20
  • Also here's something I didn't know until a few weeks ago about malloc and why you shouldn't cast the pointer: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Taelsin Dec 02 '15 at 17:41
1

Segmentation fault occur here because you are trying to access data structure to which you does not allot memory . You should allot memory for head pointer . That can be done by array->head = malloc(sizeof(smallList));

Effective code of your question is :

 #include <stdio.h>

  #include <stdlib.h>


  #define N 3


  typedef struct smallList{

      int x;

      struct smallList *next;

  }smallList;


  typedef struct bigList{

      int count;

      struct bigList *next;

      smallList *head;

  }bigList;


  void main(void)

  {
      bigList *array = malloc(sizeof(bigList));
    array->head = malloc(sizeof(smallList));
      array->count = 3;
      printf("%d \n", array->count);

      array->head->x = 10;
      printf("%d \n", array->head->x);

  }
Punit Vara
  • 3,744
  • 1
  • 16
  • 30