【发布时间】:2016-09-14 09:42:47
【问题描述】:
我目前正在学习 C,现在正在学习链表。我想我围绕着最基本的概念展开了思考。现在我想打印这样一个列表。我实现了自己的方法来打印列表的内容,但它们效率不高。我找到了 learn-c.org 并且非常喜欢他们的方法,但我似乎无法使用它。
他们的方法如下:
void print_list(node_t * head) {
node_t * current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}
我创建了一个名为“head”的节点
node_t * head = malloc(sizeof(node_t));
并尝试使用“head”作为参数调用该方法,这显然是错误的。意思是:print_list(head) 显示“冲突类型”错误。
有人对此有任何意见吗?我已经尝试过了,据我了解,该方法需要一个指向 node_t 结构的指针。
编辑:完整代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node {
int val;
struct node * next;
} node_t;
int main(){
node_t * head = malloc(sizeof(node_t));
if (head == NULL) {
return 1;
}
head->val = 1;
head->next = NULL;
print_list(head);
}
void print_list(node_t * head) {
node_t * current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}
【问题讨论】:
-
请显示您的代码,而不是公开它。
-
这应该可以,请发帖minimal reproducible example。
-
您记得在调用
print_list之前声明它的原型吗?除了 MCVE,能否请您包括完整且未经编辑的完整错误输出以及任何信息说明。 -
对不起,添加了所有内容。
-
将
print_list移动到main上方或添加原型。注意编译器警告,甚至更好的是,使用标志将警告变成错误。这会对你有很大帮助。