C 链表初学者
我刚开始学习链表,我在创建一个函数来读取我的链表时遇到了问题。当我从开关中选择read函数时,它将变为空白,如果我将代码放在main中,则不会发生任何事情,它将工作。我做错了什么C 链表初学者,c,list,C,List,我刚开始学习链表,我在创建一个函数来读取我的链表时遇到了问题。当我从开关中选择read函数时,它将变为空白,如果我将代码放在main中,则不会发生任何事情,它将工作。我做错了什么 #include<stdio.h> #include<string.h> #include<stdlib.h> struct nod { int nr; struct nod *next; } nod; int read(struct nod *p) {
#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);
}
一些建议,没有完全解决 无需将指针初始化为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));
我不清楚氮和磷是否需要分配。我想你是说它们指向分配的节点
可以使用c99语法在一条语句中初始化结构。我认为这个表格更清楚
*unu = (struct nod) { .nr = 1, .next = doi };
*doi = (struct nod) { .nr = 2, .next = trei };
*trei = (struct nod) { .nr = 3, .next = NULL };
帮自己一个忙,不要调用函数read,除非
表示覆盖标准read2函数。你不是
雷丁,你在报道。也许可以称之为印刷
这个循环很尴尬。你想要
while(p != NULL )
{
printf("%d", p->nr);
p=p->next;
}
原因有二:
防止传递的p为NULL
打印树
当p指向trei时,p->next为空。你不想退出
然后循环;要打印树,请指定p=p->next,然后
测试p。然后您可以删除printf%d,p->nr;之后
循环,因为p将为NULL:-
我看不出你的读取功能还有什么问题,没有理由
它不会打印你的数据。我会再洒上几滴
语句,并每次调用fflush3,以确保看到
他们我打赌你的程序做的不是你认为的。不
不过还是要担心。如果你喜欢编程,你会发现它很漂亮
正常 您不需要为p分配内存,因为您正在为p分配UNUNOUN的值。没有一个printf调用输出一个行尾字符-\n-用于刷新输出scanf%d,meniu;应为扫描%d,&meniu;read是系统/库函数的名称。为防止意外行为,请不要将自己的函数命名为与库函数相同的函数。命名为myRead.Change whilep->next!=空到whilep!=NULL甚至whilep,您可以在read中去掉额外的printf。