返回指向struct

时间:2015-11-25 14:53:09

标签: c pointers struct self-reference

我正在尝试编写一种ArrayList(struct),定义如下:

typedef struct {
    int reservedSize; // reserved size
    int size; // Size of list
    void ** pElements; //pointer to list elements
    void (*deleteArrayList)();
    void (*add)();
    void (*remove)();
    void (*set)();
    void* (*get)();
    int (*indexOf)();
    int (*len)();
    void (*clear)();
    void (*push)();
    void* (*pop)();
    int (*contains)();
    int (*isEmpty)();
    //Extras
    int (* containsAll)();
    struct ArrayList* (*clone)(); //trouble1
    struct ArrayList* (*subList)();//trouble2 
} ArrayList;

正如你所看到的,两个元素类型int和指向函数的指针,但我只有最后两个的麻烦。我有一个初始化器如下:

ArrayList* al_newArrayList(void) { 
    ArrayList* list;
    list = (ArrayList *) malloc (sizeof(ArrayList));
    list->size = 0;
    list->pElements = malloc(sizeof(void *) * 10);
    list->reservedSize = 10;
    list->add = al_add;
    list->deleteArrayList = al_deleteArrayList;
    list->remove = al_remove;
    list->set = al_set;
    list->get = al_get;
    list->indexOf = al_indexOf;
    list->len = al_len;
    list->clear = al_clear;
    list->push = al_push;
    list->pop = al_pop;
    list->contains = al_contains;
    list->isEmpty = al_isEmpty;
    list->containsAll = al_containsAll;
    list->clone = al_clone;//trouble1
    list->subList = al_subList;//trouble2
    return list;
}

该程序有效,但有运行时错误,我在以下位置发出错误引用的警告:

list->clone = al_clone;//trouble1
list->subList = al_subList;//trouble2

即使这些功能有效但程序已关闭。你有什么主意吗?错误的语法?

2 个答案:

答案 0 :(得分:4)

typedef struct {
    int reservedSize; // reserved size
    int size; // Size of list
    // ...
    struct ArrayList* (*clone)(); //trouble1
    struct ArrayList* (*subList)();//trouble2 
} ArrayList;

当编译器到达"麻烦"行没有名为struct ArrayList的类型。

有一种没有定义标记名的结构类型。

在该定义的最后,将定义一个名为ArrayList的类型(没有标记名的结构类型)。

解决方案:

定义类型struct ArrayList

typedef struct ArrayList {             // define type with tagname
    int reservedSize; // reserved size
    int size; // Size of list
    // ...
    struct ArrayList* (*clone)(); //trouble1
    struct ArrayList* (*subList)();//trouble2 
} ArrayList;

答案 1 :(得分:0)

非常感谢@pmg指点我。

typedef struct ArrayList ArrayList;
struct ArrayList{
    int reservedSize; // reserved size
    int size; // Size of list
    void ** pElements; //pointer to list elements
    void (*deleteArrayList)();
    void (*add)();
    void (*remove)();
    void (*set)();
    void* (*get)();
    int (*indexOf)();
    int (*len)();
    void (*clear)();
    void (*push)();
    void* (*pop)();
    int (*contains)();
    int (*isEmpty)();
    //Extras
    int (* containsAll)();
    struct ArrayList* (*clone)(); //trouble1
    struct ArrayList* (*subList)();//trouble2 
};