我想打印出一个'list'结构,打印出node struct中的第一个字段,然后跟踪指针字段。 但我遇到了一个问题,我无法找出原因:
(设置)
typedef struct node {
int first;
struct node* rest;
} int_list;
int_list cons(int x, int_list xs) {
int_list newlist = {x, &xs};
return newlist;
}
(有问题的代码)
int_list empty = {NULL,NULL};
void print_int_list(int_list xs) {
printf("element is : %d\n", xs.first);
printf("next element is : %d\n", (*(xs.rest)).first);
(commented since not related to the problem)
//printf("rest points to : %p\n", xs.rest);
//if (xs.rest != NULL) print_int_list(*xs.rest);
}
int main() {
int_list xs = cons(1,empty);
printf("element is : %d\n", xs.first);
printf("next element is : %d\n", (*(xs.rest)).first);
//printf("rest points to : %p\n", xs.rest);
//print_int_list(empty);
print_int_list(xs);
}
因为我已经对递归部分进行了评论,所以print_int_list现在并没有真正做任何事情。
main和print_int_list中的打印代码现在完全相同。 然后我发现主要部分打印出来:
element is : 1
next element is : 0 (which looks good since NULL = 0 in empty)
但print_int_list打印:
element is : 1
next element is : 189267603
为什么会这样?我的意思是为什么'xs的指针字段在作为参数传入时发生了变化?
答案 0 :(得分:2)
如BLUEPIXY在评论中所述,您将本地变量的地址分配给列表的“休息”字段。
您应该按照以下方式创建列表:
int_list* cons(int x, int_list* xs) {
int_list* newlist = malloc(sizeof(*newlist));
newlist->first = x;
newlist->rest = xs;
return newlist;
}
...
int_list* list = cons(1, NULL);
...
list = cons(..., list); //adding elements
...
您的打印成为:
void print_int_list(int_list* xs) {
if (xs == NULL)
return;
print_int_list(xs->rest); //Here so the list is displayed in the same order as creation, last created displayed last.
printf("element is : %d\n", xs->first);
}