dealing with array of linked list

二次信任 提交于 2019-12-03 08:24:23

The problem lies in addNode(). When the list is empty you do:

q = malloc(sizeof(struct node));

but the scope of q is limited to addNode(). You should have declared addNode() as

void addNode(struct node **q, char *d)

and adjust your code accordingly:

*q = malloc(sizeof(struct node));

and so on...

When you pass struct node *q to addNode you are giving it an address for an element in your array. If you use malloc inside, then you are overwriting this variable q, which is local to the function and now points to something different, but you haven't changed your original array. Try using a pointer to pointer to node (struct node **q).

void addNode(struct node *q, char *d){
    if(q == NULL)
        q = malloc(sizeof(struct node));

Here's the problem.

The new value of q doesn't ever get out of the function, so your array of linked lists never gets updated.

Normally the solution here is to use a double-pointer:

void addNode(struct node **q, char *d){
    if(*q == NULL)
        *q = malloc(sizeof(struct node));

And call it like so:

addNode(&nodesArr[i],word);

Then, if you malloc a new node, the value in the array will be set to point to the new node.

Jay Mistry
struct node
{

  int actual, estimated;

  char c;

  struct node *next;

} *head[4], *var[4], *trav[4];


void
insert_at_end (char c, int value, int value1)
{

  struct node *temp;

  temp = head[i];

  var[i] = (struct node *) malloc (sizeof (struct node));

  var[i]->actual = value;

  //var1=(struct node *)malloc(sizeof(struct node));

  var[i]->estimated = value1;

  var[i]->c = c;

  //printf("%d",var->estimated);

  if (head[i] == NULL)

    {

      head[i] = var[i];

      head[i]->next = NULL;

    }

  else

    {

      while (temp->next != NULL)

    {

      temp = temp->next;

    }

      var[i]->next = NULL;

      temp->next = var[i];

    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!