Ansi C链接列表我做错了什么?

时间:2012-02-18 12:30:56

标签: c

它破坏了那条线:
List_Node * node = (List_Node*) malloc(sizeof(List_Node));

失败:

1>list.c(31): error C2275: 'List_Node' : illegal use of this type as an expression
1>list.c(8) : see declaration of 'List_Node'

H FILE:

#ifndef _LIST_H
#define _LIST_H

typedef struct List_Node;

typedef struct List_Struct
{
    unsigned int count;
    struct List_Node * root;
    struct List_Node * last;
    int SizeOfData;
}List_Struct;   

#endif

C_FILE:

typedef struct List_Node
{
void * data;
struct List_Node * next;
}List_Node;

Status List__Add (List_Struct * This,void * const item)
{
    Assert(This)
    Assert(item)    

    struct List_Node * node = (List_Node*) malloc(sizeof(List_Node));
    IsAllocated(node);

    node->data = malloc(This->SizeOfData);
    IsAllocated(node->data);

    memcpy(node->data,item,This->SizeOfData);
    node->next = NULL;

    if(NULL == This->root) /*if first item to be added*/
    {
        This->root= node;
        This->last =This->root;
    }
    else
    {
        This->last->next = node;
    }

    return STATUS_OK;
}

2 个答案:

答案 0 :(得分:1)

VC编译器仅支持C89标准,因此必须在任何其他语句之前在范围的开头声明变量。

List_Add()更改为:

Status List__Add (List_Struct * This,void * const item)
{
    List_Node* node;
    Assert(This)
    Assert(item)    

    /* Don't cast return type of malloc(): #include <stdlib.h> */
    node = malloc(sizeof(List_Node));
    IsAllocated(node);

    ...
}

答案 1 :(得分:0)

您将列表节点定义为

typedef struct List_Node

然后你说struct * List_Node。

结构是不必要的。