OK, I wrote this program to try and learn about linked lists, basically if you run it, it asks you to input a name, and after you hit enter, it asks you to type 1 if you want to input another name or 0 if you don't.
If you put in a few names then hit 0 it should return the list of names you put in. But it doesnt. It works fine if you only input 1 name then hit 0 after that, but for more than one name it gets stuck.
It's stuck in the while( response ) portion of my code... but to me the while loop looks fine, if you input 0 it should exit the loop, but it doesn't... Can anyone tell why it doesn't exit? thank you
Code:
#include <stdio.h>
#include <stdlib.h>
/* declare a self-referential structure */
typedef struct elephant {
char name[1];
struct elephant* next;
}ELEPHANT;
void print_elephants( const ELEPHANT* ptr );
ELEPHANT* get_elephants(void);
main()
{
ELEPHANT* start;
start = get_elephants();
print_elephants( start );
getchar();
getchar();
return EXIT_SUCCESS;
}
/* get_elephants allocates run-time storage for nodes. It builds
the linked list and stores user-supplied names in the name
members of the nodes. It returns a pointer to the first such
node. */
ELEPHANT* get_elephants(void)
{
ELEPHANT *current, *first;
int response;
/* allocate first node */
current = first = malloc( sizeof ( ELEPHANT ) );
/* store name of first elephant */
printf( "\n\n\tNAME:\t" );
scanf( "%s", current -> name );
/* prompt use about another elephant */
printf( "\n\n\n\tAdd another? (1 == yes, 0 == no)\t" );
scanf( "%d", &response );
/* Add elephants to list until user signals halt. */
while ( response ) {
/* try to allocate another elephant node */
if ( ( current -> next =
malloc( sizeof ( ELEPHANT ) ) ) == NULL ) {
printf( "Out os memory\nCan't add more elephants\n");
return first;
}
current = current -> next;
/* store name of next elephant */
printf( "\n\n\tNAME:\t" );
scanf( "%s", current -> name );
/* prompt user about another elephant */
printf( "\n\n\n\tAdd another? ( 1 == yes, 0 == no)\t" );
scanf( "d", &response );
}
/* set link in last node to NULL */
current -> next = NULL;
return first;
}
/* print_elephants steps through the linked list pointed to by
ptr and prints the member names in each node as well as the
position of teh node in the list */
void print_elephants( const ELEPHANT* ptr )
{
int count = 1;
printf( "\n\n\n" );
while ( ptr != NULL ) {
printf( " \nElephant number %d is %s.",
count++, ptr -> name );
ptr = ptr -> next;
}
}
i've tried while ( response == 1 ) .... it still gets stuck