Not really sure whats going on here, whether Im just being a fool or something odd with the compiler.
The code below should, after calling my searchList function, take input from the user, but instead the program just terminates, not even seg faulting, it literally just ends. Something silly?
EDIT: searchNode is searchList, sorry for typo.
Cheers.
typedef struct List {
char c;
struct List *next;
}List;
List* insertNode(char c, List* t1);
List* addNode(void);
List* searchList(List *t1);
int main(void) {
List *z = addNode();
List *search_result;
char s;
while ( z != NULL) {
printf("%c", z->c);
z = z->next;
}
search_result = searchList(z);
return 0;
}
List *addNode(void) {
List *head = (List*)calloc(1,sizeof(List));
char c;
while (( c = getchar()) != '.') {
head = insertNode(c, head);
}
return head;
}
List *insertNode(char c, List* t1) {
List *tail = (List*)calloc(1,sizeof(List));
tail->c = c;
tail->next = t1;
return tail;
}
List *searchList(List *t1) {
char c;
printf("Please enter a search term");
scanf("%c", &c);
while (t1 != NULL) {
if (t1->c == c) {
return t1;
}
t1 = t1->next;
}
return 0;
}
Your program executes getchar
, and scanf
after it. After the execution of getchar
you still have a '\n'
in the buffer, and that's what scanf
reads.
You can work around this by reading the characters from the buffer, after you've read the .
character :
while (( c = getchar()) != '.') {
head = insertNode(c, head);
}
while (getchar() != '\n');