分段错误:11通过struct中的函数指针返回stuct

jon*_*eri 5 c struct pointers segmentation-fault

我试图模仿一个构造函数.我试图通过让父EJB具有一个返回指向子结构的指针的函数指针来做到这一点.任何帮助将非常感激.

#include <stdio.h>
#include "stdlib.h"

typedef struct child_t {

  char *name;

} Child;

typedef struct parent_t {

  Child (*NewChild)();

} Parent;

Child *NewChild() {
  Child *child = malloc(sizeof(Child));

  child->name = "foo";

  return child;
}

int 
main()
{
  Parent parent;

  Child child = parent.NewChild();
}
Run Code Online (Sandbox Code Playgroud)

and*_*ras 9

好像你还没有初始化parent.NewChild.在调用之前尝试将其设置为函数指针,如下所示:parent.NewChild = NewChild;.

此外,你不缺少*Child *child = parent.NewChild();

附录:通过注释,声明中也存在错误/冲突Parent:其NewChild成员函数声明返回a Child,而free方法NewChild返回a Child*.所以将成员函数指针声明为Child * (*NewChild)();.

  • 我会指出`child-> name ="foo";`可能没有做到实际意图. (2认同)
  • 我认为它应该是`Child*(*NewChild)();`在`parent`类型定义中. (2认同)

Vla*_*cow 3

我认为你的意思是以下内容

#include <stdio.h>
#include <stdlib.h>

typedef struct child_t {

  char *name;

} Child;

typedef struct parent_t {

    Child * ( *NewChild )( void );

} Parent;

Child * NewChild( void ) 
{
    Child *child = malloc( sizeof( Child ) );

    child->name = "foo";

    return child;
}

int main( void )
{
    Parent parent = { NewChild };

    Child *child = parent.NewChild();

    puts( child->name );

    free( child );
}    
Run Code Online (Sandbox Code Playgroud)

程序输出是

foo
Run Code Online (Sandbox Code Playgroud)

也就是说,您应该正确声明该函数。它的返回类型必须是指针。所以必须在结构体定义中正确声明函数指针

typedef struct parent_t {

  Child (*NewChild)();
  ^^^^^^
} Parent;
Run Code Online (Sandbox Code Playgroud)

并且需要初始化Parent类型的对象。

Parent parent = { NewChild };
Run Code Online (Sandbox Code Playgroud)

否则它具有不确定的值。