-3

我有一个纯 C 语言的简单程序,用于从文件中读取记录并将其放入链表中。我不允许使用全局变量。程序如下所示:

Here are some includes
Some #defines

Function headers for list manipulation:
 void add_item(Record * p, LL * ll);
 void print_all(LL * ll);
 void load(LL * ll);
 ...

    int main(int argc, char const *argv[])
    {

        // Sample struct defining one record
        typedef struct Record
        {
            char sign[10];
            long int isbn;
            char name[100];
            char authors[100];
            long int date;
            int id;
            struct Record * next;
        } Record;

        // Information about linked list (LL)
        typedef struct LL
        {
            Record * HEAD;
        }LL;

        // create new Linked List
        LL * ll = (LL *) malloc(sizeof(LL));

        // init 
        ll->HEAD = NULL;

        // Some other work with ll, record ...
}

// now functions its self

// add item p into ll
void add_item(Record * p, LL * ll)
{
    if (ll->HEAD == NULL)
    {
        ll->HEAD = p;
        ll->HEAD->next = NULL;
    }
    else
    {
        Record * cur = ll->HEAD;

        while(cur->next != NULL)
            cur = cur->next;
        cur->next = p;
    }
}

void print_all(LL * ll)
{
    if (!ll->HEAD)
    {
        printf("%s\n", "ll->HEAD is NULL...");
        return;
    }

    Record * cur = ll->HEAD;

    while(cur)
    {
        printf("%s\n", cur->name );
        cur = cur->next;
    }
}

// other functions

现在,当我在 Ubuntu 12.04 上使用 gcc 编译时,我得到:

project.c:20:15: error: unknown type name ‘Record’
project.c:20:27: error: unknown type name ‘LL’
project.c:21:16: error: unknown type name ‘LL’
project.c:22:11: error: unknown type name ‘LL’
project.c:145:15: error: unknown type name ‘Record’
project.c:145:27: error: unknown type name ‘LL’
project.c:162:16: error: unknown type name ‘LL’
project.c:182:11: error: unknown type name ‘LL’

我如何让编译器知道函数头struct Recordstruct LL函数头之前,何时构造其自身并在 main() 中声明?

4

1 回答 1

4

你不能。

声明必须从声明函数的同一级别可见。

将结构声明移到列表函数原型之前。

或者添加一个预先声明:

typedef struct Record Record;

只要列表函数只处理指针 ( Record *),那应该可以工作。

于 2013-05-02T14:08:49.500 回答