问题
I'm trying to create a simple singly linked list. Previously, I successfully did this with no errors, however now I encounter an error. I suspect that there is some kind of problem with memory allocation because of the if
statement in line 23.
What I've tried:
I used typecasting in all of my declarations even though it is not necessary in C.
I removed the
if
statement and I still encountered the errors.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int value;
struct Product *next;
} Product;
int main()
{
int user_choice;
Product *head;
head = malloc(sizeof(Product));
head->next = NULL;
head->value = 5;
printf("\n Do you want to add a new node (0 for no, 1 for yes)? \n");
scanf("%d", &user_choice);
if (user_choice == 1) // line 23
{
head->next = malloc(sizeof(Product));
if (!head->next)
printf("\n Memory allocation failed! \n");
head->next->next = NULL; // 1st error
printf("\n Enter a value: \n");
int value;
scanf("%d", &value);
head->next->value = value; // 2nd error
}
free(head);
free(head->next);
}
回答1:
typedef struct
{
} Product;
Declares a type alias called Product
for an unnamed struct - however you need a named struct for your forward declaration struct Product *next;
, otherwise the compiler cannot determine which definition it belongs to.
The simplest solution is to give the struct a name:
typedef struct Product
{
int value;
struct Product *next;
} Product;
来源:https://stackoverflow.com/questions/55678371/pointer-to-incomplete-class-type-is-not-allowed-singly-linked-list