c - Why is there junk data in the first node of my linked list? -


it appears there junk data in first node of list. why be?

these definitions of structs i'm using.

typedef struct node {     char *x;     struct node *next;  }node;  typedef struct {     struct node *head; }list; 

// create_list() function :

list* create_list(){     list *mylist = malloc(sizeof(mylist));     mylist->head = null;     if (mylist->head != null){         return null;      }     return mylist;   } 

here implementation of add_to_list function

int add_to_list(list* ll, char* item){      node *current = ll->head;     node *new_node = malloc(sizeof(node));     if (!new_node){         fprintf(stderr, "error allocating mem.\n");         return 1;     }     strcpy(new_node->x, item);     new_node->next = null;     if(ll->head == null){        ll->head = new_node;        return 0;     }else{        while(current->next){        current = current->next;     }      current->next = new_node;    }   return 0; } 

this print_list(); funcntion

void print_list(list *ll){      node *current = ll->head;     while(current){        printf("%s\t\n",current->x);        current = current->next;     } } 

when call function in main.c here how i'm doing :

list *newlist = create_list();  char test_var = 'k';  add_to_list(newlist, &test_var);  printf("printing whole list : \n");  print_list(newlist); 

it because passing char char pointer (ie string). change

char test_var = 'k';  

to

char *test_var = "k"; 

and change call to

add_to_list(newlist, &test_var) 

to

add_to_list(newlist, test_var) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -