转换void指针

时间:2014-02-06 14:37:30

标签: pointers struct casting

我有一个结构

struct GROUP_POINTS
{
   unsigned char number_of_points;
   void *points;
};

struct GROUP_POINTS group_points;

点作为void指针的原因是我希望尽可能保持组的通用性,并在运行时将“link”设置为正确的结构。

其他结构之一是:

struct POINT_A
{
   unsigned char something;
};

我可以创建另一个指向*点的指针来访问结构,如:

struct POINT_A *point_a = (struct POINT_A *)group_points.points;

然后通过执行以下操作来访问这些点:

(*point_a).number_of_points = 5;

但我真的希望能够像这样使用它:

group_points.points.number_of_points

所以不需要第二个指针只是指向void指针。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

假设语言是C ++,您可能需要考虑模板解决方案:

template <class T>
struct GROUP_POINTS
{
   unsigned char number_of_points;
   T *points;
};

typedef GROUP_POINTS<unsigned char> POINT_A;
//another typedefs for another points. 

另外,你可能只使用std::vector<T>而不是整点结构,但只是为了说明一般方法,这就是它的完成方式。

答案 1 :(得分:0)

由于你只需要避免使用另一个指针,你可以像这样使用它:

((struct POINT_A *)group_points).points.number_of_points = 5;

请注意,类型转换的优先级低于.运算符的优先级,括号是必需的。

相关问题