简体   繁体   English

根据输入参数将 void 指针转换为另一种类型

[英]Cast a void pointer to another type based on an input parameter

I am trying to create a variable of type A or B based on an input parameter and assign a casted void pointer to it.我正在尝试根据输入参数创建 A 或 B 类型的变量,并为其分配一个强制转换的 void 指针。

void set_info_param(void* info, bool req)
{
    ...
    if (req)
        struct info *capa_info = (struct info *) info;
    else
        struct info_old *capa_info = (struct info_old *) info;
    ... [Use capa_info]
}

When I try to compile it I get the following error:当我尝试编译它时,我收到以下错误:

expected expression before 'struct' 'struct' 之前的预期表达式

Since you define new variables you need to put it into blocks like:由于您定义了新变量,因此您需要将其放入块中,例如:

if (req)
{
    struct info *capa_info = (struct info *) info;
    ...
}
else
{
    struct info_old *capa_info = (struct info_old *) info;
    ...
}

In C declarations are not statements.在 C 中,声明不是语句。

On the other hand, the if statement expects a sub-statement.另一方面,if 语句需要一个子语句。

So if you want that the sub-statement of the if statement had a declaration then enclose the declaration in the compound statement like因此,如果您希望 if 语句的子语句具有声明,则将声明包含在复合语句中,例如

if (req)
{
    struct info *capa_info = (struct info *) info;
}
else
{
    struct info_old *capa_info = (struct info_old *) info;
... [Use capa_info]
}

I am trying to create a variable of type A or B我正在尝试创建 A 或 B 类型的变量

This is not how C types works.这不是 C 类型的工作方式。 Every variable has a type which is known statically at compile time.每个变量都有一个在编译时静态已知的类型。 You cannot have a variable assume one of the two types based on a run-time condition.您不能让变量根据运行时条件假定这两种类型中的一种。 If you need two different types, you have to use two different variables.如果您需要两种不同的类型,则必须使用两个不同的变量。

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

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