【发布时间】:2016-06-10 12:18:06
【问题描述】:
我做了一个这样的简单列表:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
struct node{
int am;
struct node *next;
};
typedef struct node node;
int main(){
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->next=null;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
system("pause");
return 0;
}
现在 travel 应该遍历列表中的每个节点,并显示每个节点中保存的整数。
void travel(node *h){
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
现在的问题是,当调用 travel 时,它不会从第一个节点打印整数。它还会打印另一个“从节点接收的数据:”,后跟一个奇怪的数字。 例如 如果我给出 1,2,3,4 作为输入,这些就是结果
Received data from node: 2
Received data from node: 3
Received data from node: 4
Received data from node: 4026432
有什么想法吗?
【问题讨论】:
-
没有直接关系,但递归遍历列表是个糟糕的主意。
-
scanf(" %d",head->am);使它成为scanf("%d",&head->am); -
启用编译器警告或获得更好的编译器。
-
-
为什么不呢?你能准确点吗....
head->am不是变量的地址。
标签: c list data-structures