c - 在c中传递和分配指向void*的指针

标签 c void-pointers generic-programming

我在 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/

相关文章:

c - 交叉编译问题

c++ - 将带有参数的回调函数传递给函数

c++ - 如何摆脱 -Wpointer-arith

vhdl - "template"VHDL实体

scala - 为什么 deriveHCons 的签名在 Symbol 是最终类时声明 `HK <: Symbol`

c - 函数中的参数;不同的结果

c - 从设备包含的文件中的 st_dev 字段查找设备文件

c - 获取日期并将其保存在结构体 C 中

c++ - 空基优化子对象的地址

c++ - 在 STL 容器中使用模板类