简体   繁体   English

c中typedef结构中的函数指针

[英]function pointer in typedef struct in c

I have been working on this code and keep coming across a segmentation fault.我一直在研究这段代码并不断遇到分段错误。 I am almost positive that it is coming from how I initialized my function point in the OBJ_T type.我几乎肯定它来自我如何在 OBJ_T 类型中初始化我的函数点。 Here's what I have:这是我所拥有的:

typedef struct obj
{
    COLOR_T color;
    int (*intersect)(RAY_T ray, struct obj, VP_T *int_pt, VP_T *normal, double *t);

    union geom
    {
       SPHERE_T sphere;
       PLANE_T plane;
    }geom;

} OBJ_T;

This is the line I get the seg fault:这是我得到段错误的行:

if((*(objs[i].intersect))(ray, objs[i], &int_pt, &normal, &t) == 1)

if((*(objs[i].intersect))(ray, objs[i], &int_pt, &normal, &t) == 1) if((*(objs[i].intersect))(ray, objs[i], &int_pt, &normal, &t) == 1)

The memory is not allocated for that pointer that time you will get the segmentation fault.没有为那个指针分配内存,那个时候你会得到分段错误。

To solve this, fist you have to allocate the memory for the structure member.要解决这个问题,首先必须为结构成员分配内存。

int (*intersect)(RAY_T ray, struct obj, VP_T *int_pt, VP_T *normal, double t); int (*intersect)(RAY_T ray, struct obj, VP_T *int_pt, VP_T *normal, double t);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM