【问题标题】:passing and allocating pointer to void* in c在c中传递和分配指向void *的指针
【发布时间】: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*来匹配Result typedef。

标签: c void-pointers generic-programming


【解决方案1】:

问题是您将指向firstPhase(在Func() 中定义)的指针传递给registerMen100m() 函数的firstPhase 参数,但是,作为函数中的第一件事,您用地址覆盖它一个新分配的内存块。

之后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 在两个不同的功能中具有两种不同的含义,这使得很难推断正在发生的事情。 此外,您很少需要将函数作为参数传递。您以这种方式构建程序有什么具体原因吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2019-12-13
    • 2013-10-19
    • 2012-03-15
    • 2013-01-08
    相关资源
    最近更新 更多