指向函数的指针 return 指向结构的指针

pointer to function that return pointer to struct

我正在尝试编写一种定义如下的 ArrayList(结构):

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

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

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

当编译器到达 "trouble" 行时,没有名为 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;

非常感谢@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 
};