I am trying to make a C language program with a linked list that uses recursion to count the total of the linked list nodes. However, I get this error:
passing argument 1 of 'count' from incompatible pointer type [-Wincompatible-pointer-types]|
Can anyone explain to me why this happen and how to fix it?
This is linked list node without recursion. It works without error and gives return the value that I need.
int count(list_t *list){
node_t *curr = list->head;
int length=0;
while(curr != NULL){
length++;
curr = curr->next;
}
return(length);
}
And this one is recursive, but I get the "'count' from incompatible pointer" error.
int count(list_t *list){
node_t *curr = list->currptr;
int length=0;
if(curr == NULL){
return(0);
}
return(1 + count(curr->next));
}
This is structure of my linked list
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;
The output should be 8 but the program is terminated with:
Process returned -1073741819 (0xC0000005) execution time : 5.093 s
I'm still new to StackOverflow. My apologies if I said something wrong.
Thank you for posting the definitions. That is very helpful. For recursion, you only need to deal with the node_t
and not the list_t
. It might look like this:
int count(node_t *curr)
{
if (curr == NULL)
{
return (0);
}
return (1 + count(curr->next));
}
Then you call it like this:
count(list->head);
If you want to be able to call it with a list_t
, then add a helper function like this:
int countList(list_t *list)
{
return count(list->head);
}
Here is a different suggestion, if you want to have one function that handles both list_t
and node_t
:
int count(list_t *list, node_t *curr)
{
if (list == NULL)
{
if (curr == NULL)
{
return (0);
}
return (1 + count(NULL, curr->next));
}
else
{
return count(NULL, list->head);
}
}
I don't like this way, but I'm trying to give you some options to consider. I think my first answer, that just deals with node_t
and not using list_t
is the best solution.
User contributions licensed under CC BY-SA 3.0