我刚刚开始学习链接列表,我有问题,做一个功能,将阅读我的链接列表。当我从开关中选择read函数时,它变为空白,什么也不会发生(如果我将代码放在main ()中,它就会工作)。我做错了什么?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct nod
{
int nr;
struct nod *next;
} nod;
int read(struct nod *p)
{
while(p->next != NULL )
{
printf("%d", p->nr);
p=p->next;
}
printf("%d", p->nr);
}
int main()
{
struct nod* trei = NULL;
struct nod* unu = NULL;
struct nod* doi = NULL;
struct nod* p = NULL;
struct nod* n = NULL;
unu = (struct nod*)malloc(sizeof(struct nod));
doi = (struct nod*)malloc(sizeof(struct nod));
trei = (struct nod*)malloc(sizeof(struct nod));
p = (struct nod*)malloc(sizeof(struct nod));
n = (struct nod*)malloc(sizeof(struct nod));
unu->nr = 1;
unu->next = doi;
doi->nr = 2;
doi->next = trei;
trei->nr = 3;
trei->next = NULL;
p = unu;
int meniu = 0;
while(1)
{
printf("1. Read list");
scanf("%d", meniu);
switch(meniu)
{
case(2):
read(p);
break;
}
}
printf("%d", p->nr);
}发布于 2019-01-24 16:37:56
几个建议,没有完全的解决办法。
不需要将指针初始化为NULL,只需在一步内定义和初始化。另外,不要从void*中强制转换,这是malloc返回的内容。C允许您隐式地从空指针之间来回转换;每个强制转换都是出错的机会。
struct nod* trei = malloc(sizeof(struct nod));
struct nod* unu = malloc(sizeof(struct nod));
struct nod* doi = malloc(sizeof(struct nod));我不清楚n和p是否需要分配。我认为您的意思是指向已分配的节点。
您可以使用c99语法在一条语句中对结构进行无效化。我想这个表格要清楚得多。
*unu = (struct nod) { .nr = 1, .next = doi };
*doi = (struct nod) { .nr = 2, .next = trei };
*trei = (struct nod) { .nr = 3, .next = NULL };帮自己一个忙,不要调用函数read,除非您打算重写标准的read(2)函数。你不是在读书,你是在报告。也许叫它“打印”。
这个回路很尴尬。你想要的
while(p != NULL )
{
printf("%d", p->nr);
p=p->next;
}原因有二:
p为空trei当p指向trei时,p->next为NULL。那么,您不希望退出循环;您希望打印trei、分配p = p->next和测试p。然后,您可以在循环之后删除printf("%d", p->nr);,这是必须的,因为p将为NULL。:-)
我看不出你的“读取”函数还有什么问题,它没有理由不打印你的数据。我会在其中再添加几个printf语句,每次调用fflush(3),以确保您看到它们。我敢打赌你的程序不会像你想的那样。不过不用担心。如果你喜欢编程,你会发现这很正常。
https://stackoverflow.com/questions/54347945
复制相似问题