【发布时间】:2020-05-29 21:39:11
【问题描述】:
下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
struct node {
int data;
struct node *next;
};
int choice;
struct node *head, *newnode, *temp;
head = 0;
while (choice) {
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter items ");
scanf("%d", &newnode->data);
newnode->next = 0;
if (head == 0) {
head = temp = newnode;
} else
temp->next = newnode; /** **this is the problem** **/
temp = newnode; /** temp=newnode works but temp=temp->next doesn't**/
printf("do you want to continue");
scanf("%d", &choice);
}
temp = head;
while (temp != 0) {
printf("list is %d \n", temp->data);
temp = temp->next;
}
}
【问题讨论】:
-
else语句后面的两行不应该有花括号吗? -
大括号后问题解决;但是该列表甚至在此之前就可以正常工作而没有出现任何错误,您能解释一下为什么会这样吗?
-
@user12552749 如果您可以在添加花括号之前提供列表的输出或行为差异,也许我可以帮助解释
-
旁注:你的代码做任何事情纯属意外,你还没有初始化
choice,如果它意外地为0,那么你根本不会进入你的循环。您应该将其初始化为 != 0 - 或将循环转换为 do-while,然后在scanf中分配之前不会读取choice。 -
建议:总是在 if 块或循环的主体周围放置大括号,即使您不需要(许多编码指南也强制要求,尤其是 MISRA)。如果您稍后扩展该行,这将避免忘记放置它们,但更重要的是,它可以防止在看似函数实际上是(错误定义的)多表达式宏(类似于
#define f() g(); h();)的情况下出现错误。如果您不想跟随,那么至少可能是这个:如果您在 any 的不同分支中有大括号,则将它们放在 all 周围。
标签: c pointers linked-list