pointer to incomplete class type is not allowed - singly linked list

此生再无相见时 提交于 2019-12-04 05:02:54

问题


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:

  1. I used typecasting in all of my declarations even though it is not necessary in C.

  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!