开发者

Using Pass by reference with linked lists

开发者 https://www.devze.com 2023-02-19 18:00 出处:网络
So I\'ve use pass by reference 开发者_开发百科on my linked list code but the problem is it\'s not printing soo how doI actually fix this?

So I've use pass by reference 开发者_开发百科on my linked list code but the problem is it's not printing soo how do I actually fix this?

my code:

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

struct node
{
      int x;
      struct node *next;
};

void add(struct node **root, int x)
{
      struct node *conductor;
      if(root==NULL)
      {
          (*root)=malloc(sizeof(struct node));
          (*root)->x=x;
          (*root)->next=NULL ;         
      }
      else
      {
          conductor = *root;
          while(conductor->next!=NULL)
          {
              conductor = conductor -> next;             
          }
          conductor->next=malloc(sizeof(struct node));
          conductor->next->x=x;
          conductor->next->next=NULL;
      } 
}      

void display(struct node *root)
{
      struct node *conductor;
      conductor=root;
      while(conductor!=NULL)
      {
           printf("%d",conductor->x);
           conductor = conductor ->next;                           
      } 
}



int main()
{
    struct node *root;
    root=NULL;
    add(&root,5);
    add(&root,4);
    display(root);
    free(root);
    system("pause");
 }

In better form http://codepad.org/CPdUvK0x

Isn't it all nodes in my program are linked?


void add(struct node **root, int x)
 {
      struct node *conductor;
      if(root==NULL)

That should be if (*root == NULL)

Since you're calling add(&root... root will never be NULL.


The check:

if(root==NULL)

should be

if(*root==NULL)

as root is being passed by address.

Also you do free(root) to free the entire list which is incorrect as it frees only the first node and makes the other nodes unreachable causing memory leak. To fix this you need to free the nodes one by one as:

struct node *tmp = root;
while(root) {
  tmp = root->next;
  free(root);
  root = tmp;
}


the problem is in add():

if(root==NULL)

this test is wrong: root being passed by reference is never NULL (see in the main, it contains the address of the root node). you should correctly test if the rrot node is NULL:

if (*root == NULL)

i would also add that your way of freeing the memory allocated for the ist is wrong:

free(root)

will only free the root node, but will leak the child nodes...

0

精彩评论

暂无评论...
验证码 换一张
取 消