首页 > 解决方案 > 如何从不兼容的指针类型中修复传递“count”的参数 1

问题描述

我正在尝试制作一个带有链表的 C 语言程序,该链表使用递归来计算链表节点的总数。但是,我收到此错误:

passing argument 1 of 'count' from incompatible pointer type [-Wincompatible-pointer-types]|

谁能向我解释为什么会发生这种情况以及如何解决?

这是没有递归的链表节点。它可以正常工作并返回我需要的值。

int count(list_t *list){
    node_t *curr = list->head;
    int length=0;
    while(curr != NULL){
        length++;
        curr = curr->next;
    }
    return(length);
}

这个是递归的,但我从不兼容的指针中得到“'count'”错误。

int count(list_t *list){
    node_t *curr = list->currptr;
    int length=0;
    if(curr == NULL){
        return(0);
    }
    return(1 + count(curr->next));
}

这是我的链表的结构

typedef struct {
    int yyyy, mm,dd;
} date_t;

typedef struct {
    double balance;
} acc_balance;

typedef struct node node_t;

struct node{
    char *acc_no, *name, *lastname;
    date_t date;
    acc_balance acc_balance;
    node_t *next;
};

typedef struct {
    node_t *head;
    node_t *foot;
    node_t *currptr;
} list_t;

输出应为 8,但程序以以下方式终止:

Process returned -1073741819 (0xC0000005) execution time : 5.093 s

我还是 StackOverflow 的新手。如果我说错了,我很抱歉。

标签: crecursionlinked-list

解决方案


感谢您发布定义。这很有帮助。对于递归,您只需要处理node_t而不是list_t. 它可能看起来像这样:

int count(node_t *curr)
{
    if (curr == NULL)
    {
        return (0);
    }
    return (1 + count(curr->next));
}

然后你这样称呼它:

count(list->head);

如果您希望能够使用 a 调用它list_t,则添加一个辅助函数,如下所示:

int countList(list_t *list)
{
    return count(list->head);
}

推荐阅读