c - Printing Names using Circular Linked List -
c - Printing Names using Circular Linked List -
i working on circular linked list problem , solved it.but got stuck in other problem. programme takes names of persons in circular linked list nodes , prints them.
my question programme works fine if , if names 4 characters or less.if length of names exceeds 4,it shows weird behaviour.
if length of name 5 characters,then programme stuck on sec iteration of loop of initiate function.
if length of name 6 characters or more programme terminates showing names entered.
the source code is:
#include <stdio.h> #include <stdlib.h> #include <strings.h> #define size 10 #define num_per_line 3 typedef struct node { char name[size]; struct node * next; } clistnode; void get_name(char *a); void print_list(clistnode *end_ptr); clistnode *initiate(int n); clistnode *insert_at_end(clistnode *first,clistnode *end_ptr, char *a); int main(void) { clistnode *list_end_ptr; int n=6; list_end_ptr=initiate(n); print_list(list_end_ptr); homecoming 0; } void get_name(char *a) { char *aa=(char *)malloc(10*sizeof(char)); a=aa; scanf("%s", a); } clistnode *insert_at_end(clistnode *first,clistnode *end_ptr, char *a) { clistnode *temp, *head=null; head=first; temp=(clistnode *) malloc(sizeof(clistnode)); end_ptr->next=temp; strcpy(temp->name, a); temp->next=head; homecoming temp; } clistnode *initiate(int n) { clistnode *end, *first=null,*ptr=null; int i; char new_name; end=(clistnode *) malloc(sizeof(clistnode)); if (end==0) { printf("allocation error...\n"); exit(0); } end->next=end; (i=0; i<n; i++) { if (i<1) { printf("enter name of %d person: ", i+1); get_name(&new_name); strcpy(end->name, &new_name); first=end; } else { printf("enter name of %d person: ", i+1); get_name(&new_name); ptr=insert_at_end(first,end, &new_name); end=ptr; } } homecoming end; } void print_list(clistnode *end_ptr) { int i=1; clistnode *str_ptr; if (end_ptr == null) printf("\n list empty"); else { str_ptr = end_ptr->next; while (str_ptr != end_ptr) { printf("%s \t", str_ptr->name); str_ptr = str_ptr->next; if (i%num_per_line==0) { printf("\n"); } i++; } printf("%s\n", str_ptr->name); } }
the problem in get_name
function , way utilize it. signature assumes storage allocated, because take pointer, not pointer pointer. code ignores allocation completely; on top of that, passes pointer character.
since allocate name
within node, remove malloc
, remove new_name
, , pass name
array get_name
:
void get_name(char *a) { scanf("%9s", a); // limit size 9 chars } ... printf("enter name of %d person: ", i+1); get_name(end->name);
c linked-list
Comments
Post a Comment