【发布时间】:2017-01-03 21:41:55
【问题描述】:
我在 c 中使用函数指针来创建通用结构。 当我调用特定函数时,其中一个参数是输出参数。我在特定函数内分配内存,但它不起作用。希望得到一些帮助!
typedef void *PhaseDetails;
typedef Result (*Register)(const char *, PhaseDetails *);
Result Func(const char *file, Register register1){
PhaseDetails firstPhase = NULL;
Result res = register1(file, &firstPhase);
}
int main() {
OlympicSport os = Func("men100mList.txt", (Register) registerMen100m);
return 0;
}
Result registerMen100m(const char *file,
Men100mPhaseDetails *firstPhase) {
firstPhase = malloc(sizeof(*firstPhase));
if (firstPhase == NULL) {
return OG_MEMORY_ALLOCATION_FAILED;
}
*firstPhase = malloc(sizeof(**firstPhase));
(*firstPhase)->phaseName = malloc(sizeof(char)*12);
return OG_SUCCESS;
}
问题在于firstPhase 返回为NULL
【问题讨论】:
-
你永远不会打电话给
Func。应该是Result osCreate? -
因为参数是按值传递的(如果您愿意,也可以复制),所以它不会被函数修改(函数修改它的副本)。添加另一个间接级别。 (请注意,您的大部分代码都是错误的、错误的函数调用、类型等)。
-
“添加另一个间接级别”是什么意思?
-
函数参数应该是
PhaseDetails *firstPhase。然后它应该做*firstPhase = malloc(sizeof(Men100mPhaseDetails)) -
为什么函数中有两个
malloc()调用?第二个是正确的。但是参数类型不对,应该是PhaseDetails*来匹配Resulttypedef。
标签: c void-pointers generic-programming