【问题标题】:Printing linked lists in C在 C 中打印链表
【发布时间】: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 上方或添加原型。注意编译器警告,甚至更好的是,使用标志将警告变成错误。这会对你有很大帮助。

标签: c pointers


【解决方案1】:

当您调用print_list 时,编译器不知道它是什么。您必须在使用之前声明您使用的所有内容。

类似

// Declare the function prototype, so compiler knows about it
void print_list(node_t * head);

int main(void)
{
    node_t * head;

    // Create and populate list...

    print_list(head);

    return 0;
}

// Define the function implementation
void print_list(node_t * head)
{
    // The implementation of the function...
}

【讨论】:

    【解决方案2】:

    你没有声明原型:

    ...
    typedef struct node {
      int val;
      struct node * next;
    } node_t;
    
    void print_list(node_t * head);  // <<< add this
    
    int main() {
    ...
    

    在 C 语言中,即使没有声明函数,您也可以使用函数,然后编译器会隐式假定该函数具有任意数量的参数并且它返回一个 int。这是非常古老的 C 标准的遗留物。如果您这样做,现代编译器通常会发出警告。

    你的情况会发生什么:

    • 编译器偶然发现print_list(head);,假设它返回int
    • 然后它偶然发现void print_list(node_t * head) {,突然返回类型不再是int,而是void,因此出现编译错误。

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多