i'm trying program inserts , deletes students linked list , when try insert student @ end of list doesn't work. i'm pretty sur function algorithm right, still. anyways, here's code:
void insetend(){ stud *temp, *newnode; char n[15]; int a; printf("student: \n"); printf("name: "); scanf("%s", n); printf("age: "); scanf("%d", &a); strcpy(newnode->name, n); newnode->age=a; temp=head; while(temp!=null){ temp=temp->next; } temp = (stud *) malloc (sizeof(stud)); newnode->next = null; temp->next = newnode; }
for starters pointer newnode
has indeterminate value. these statements
strcpy(newnode->name, n); newnode->age=a;
result in undefined behavior.
this loop
while(temp!=null){ temp=temp->next; }
does not make sense because evident after loop pointer temp
equal null
.
and have change last pointer in list after new node inserted.
the function can @ least following way (though using function scanf
character array used in program unsafe)
void insetend() { stud *newnode; stud **temp; char n[15]; int a; printf("student: \n"); printf("name: "); scanf("%s", n); printf("age: "); scanf("%d", &a); newnode = ( stud * )malloc( sizeof( stud ) ); strcpy( newnode->name, n ); newnode->age = a; newnode->next = null; temp = &head; while ( *temp != null ) temp = &( *temp )->next; *temp = newnode; }
Comments
Post a Comment