gpt4 book ai didi

c - 链表麻烦

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:10 27 4
gpt4 key购买 nike

有谁知道下面的代码可能有什么问题?当我运行它时,我得到以下输出:

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( "%c", &ch );

...为此:

scanf( "\n%c", &ch ); // << Note, \n to pickup newline before reading the value.

关于c - 链表麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com