我在 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
最佳答案
问题在于您将指向 firstPhase
的指针(在 Func()
中定义)传递到 的
函数,但是,作为函数中的第一件事,您可以使用新分配的内存块的地址覆盖它。firstPhase
参数中registerMen100m()
此后,Func()
函数中 firstPhase
的值不会也不可能在 registerMen100m()
内更改
Result registerMen100m(const char *file, Men100mPhaseDetails *firstPhase)
{
/* At this point, firstPhase holds the address of the variable
** 'firstPhase' you defined in the 'Func()' function.
*/
firstPhase = malloc(sizeof(*firstPhase));
/* And now it doesnt! So you will never be able to get anything back
*/
if (firstPhase == NULL) {return OG_MEMORY_ALLOCATION_FAILED;}
/* The result of the following malloc is stored in the memory space you
** allocated earlier! If you remove the two lines above you
** should most probably get what you wanted.
*/
*firstPhase = malloc(sizeof(**firstPhase));
(*firstPhase)->phaseName = malloc(sizeof(char)*12);
return OG_SUCCESS;
}
作为一般性评论,只有当到处都表示相同的意思时,使用相同的名称才有意义。这里的 firstPhase
在两个不同的函数中具有两种不同的含义,这使得很难推断发生了什么。
此外,您很少需要将函数作为参数传递。您以这种方式构建程序有什么具体原因吗?
关于c - 在c中传递和分配指向void*的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39179472/