[英]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;
到编译器到达“麻烦”行时,还没有名为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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.