c - 指向返回结构指针的函数的指针

标签 c pointers struct self-reference

我正在尝试编写一种定义如下的 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;

当编译器到达“问题”行时,没有名为 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;

关于c - 指向返回结构指针的函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919592/

相关文章:

C: 如何将字符串存储到 “char *myArray[100]” 数组中?

c - 声明 char 数组导致 execv() 不起作用

c++ - 我如何使用 gcc 的内联报告 (-Winline)

c - 访问结构中指针(变量)结构的成员

c - 指针别名可以在 C 中的 free() 函数中工作吗

c - 未创建多个队列 - C

c++ - valgrind 中的 helgrind 提示简单的互斥锁

C 数组打印段错误?

c - struct 中带有空格的字符串 - 不起作用

c++ - 在 C++ 中删除多维结构会导致访问冲突