我尝试用C编程初始化一个带有另一个结构指针的结构指针,否则我得到了分段错误。结构定义如下:
`struct gfcontext_t{
char *fileContent;
size_t fileLength;
char *response;
int socket_hd;
};
struct gfserver_t{
char *serverName;
int serverPort;
int maxConnection;
ssize_t (*handler)(struct gfcontext_t *, char *, void * );
struct gfcontext_t *ctx;
int status;
};
初始化是在函数内部给出的:
gfserver_t * gfserver_create(){
struct gfserver_t *gfs;
gfs=(gfserver_t*) malloc(sizeof(struct gfserver_t));
......//how to do the initialization?
return gfs;
}`
答案 0 :(得分:1)
使用:
gfs->ctx = malloc(sizeof(struct gfcontext_t));
或者如果您还想将gfcontext_t成员初始化为null
gfs->ctx = calloc(1, sizeof(struct gfcontext_t));