有谁知道下面的代码可能是什么问题?当我运行它,我得到以下的输出:链接列表问题
Insert a value in the list: 1
Do you want to continue? y/N:
1 ->
的事实是,do-while循环执行,直到scanf("%c", &ch)
语句,然后它跳了出来(所以我不能提供的ch
变量的任何输入) 。我试着用GDB进行调试,我得到了一些奇怪的信息:
GI___libc_malloc (bytes=16) at malloc.c:malloc.c: No such file or directory.
此外,它说,编译器找不到vscanf.c
文件。有没有人对这种奇怪的行为有解释?谢谢! (其目的是为了以倒序打印单链表的值。)
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node* next;
};
struct node* head = 0;
void add_node(int value){
struct node* current = malloc(sizeof(struct node));
current->info = value;
current->next = head;
head = current;
}
void print_node(struct node* head){
while(head){
printf(" %d -> ", head->info);
head = head->next;
}
printf("\n");
}
int main(void){
int val;
char ch;
do {
printf("Insert a value in the list: ");
scanf("%d", &val);
add_node(val);
printf("Do you want to continue? y/N: ");
scanf("%c", &ch);
} while(ch == 'y' || ch == 'Y');
printf("\n");
print_node(head);
return 0;
}
这里是一个完整的镜头,第二个'scanf'可以在换行符中读取吗? –
将add_node的方法签名更改为接受struct node *参数,然后将head的地址作为参数传递给您的函数调用。这应该做到这一点。 – Clocks
GDB消息用于通知您无法步入GLIB文件,只需按c继续。 – Clocks