从结构内部的void指针访问结构的成员



我想从结构内部的void指针访问结构的成员,我已经尝试了以下代码,但它给出了"在'('token之前的预期标识符"的错误。我应该在printf语句中更改什么?提前感谢。

#include "stdio.h"
struct
{
    int date;
    char *name;
}test;
struct
{
    void *check;
}massage;
main()
{
    test.date=21;
    test.name="Nilesh";
    massage.check =&test;
    printf("date - %d , name - %sn",massage.((struct test *)check)->date,massage.((struct test *)check)->name);
}
struct  // anonymous struct type 
{
    int date;
    char *name;
} test;

上面的语句定义了一个匿名结构类型,并创建了一个没有名称的此结构类型的变量test。类似地,下面的语句定义了一个匿名结构类型,并创建了一个类型为的变量massage

struct  // anonymous struct type
{
    void *check;
} massage;

typecast运算符的括号中必须有一个类型(type),而不是变量名。因此,必须为第一个struct指定一个名称(标记),以便使用typecast运算符此外,typecast运算符的结果是r-value,因此它不能与成员选择.(dot)运算符一起使用(它应该是成员的名称)。因此,应该在从结构中提取值之后应用类型转换运算符因此,以下表达式是错误的-

massage.((struct foo *)check)->date
//      |____________________|
//                |
//       this should be the member name but it
//       evaluates to a r-value - the result of
//       the typecast operator assuming struct tag
//       is foo
// it should instead be
((struct foo *)massage.check)->date
// dot operator has higher precedence than typecast
// so the struct member check is fetched first and 
// it is typecast to type (struct foo *)

我建议进行以下更改-

// standard headers should be 
// enclosed in angle < > brackets
#include <stdio.h>
// give the structure a name so it can be 
// used in typecasting
struct foo {  
    int date;
    char *name;
} test;
// anonymous struct type
struct {
    void *check;
} massage;
// return type of main should be int and 
// parameter list should contain void
int main(void) {
    test.date = 21;
    test.name = "Nilesh";
    massage.check = &test;
    // fetch the struct member check and then 
    // apply typecast operator
    printf("date - %d , name - %sn", ((struct foo *)massage.check)->date, 
                                      ((struct foo *)massage.check)->name);
    return 0;
}

在您的表达式中:

massage.((struct test *)check)->date
//               ^^^ is variable not a data-type 

有两个错误:

  1. 不能在变量中键入case,在代码中test是一个变量而不是类型,因此(struct test *)是错误的表达式。您应该命名用户定义的类型(正如我在下面建议的那样)。

  2. 您正在应用类型转换,而没有访问massage的指针成员。所以在表达式(struct test *)check中,实际上"check"是未知变量。编译器将错误地检查未声明的变量(认为test不是数据类型,但应用类型转换的顺序在概念上是错误的)。

我建议尝试几个修正:

  1. 将灰泥命名为例如newtype

     struct newtype  // notice I given name to user defined datatype
     {
        int date;
        char *name;
     }test;
    
  2. 然后纠正printf函数中的第二个和第三个参数,如下所示

      ((struct newtype *)massage.check)->date
     // ^^^^^^^^^^^^^^ notice  
    

类似于printf中的第三个参数。首先访问成员,然后键入转换为正确类型的类型。

有关完整代码,请参阅Ajay的回答。

结构定义不是您想要的--它定义了一个未命名结构类型的对象测试。尝试

struct testType
{
    int date;
    char *name;
} test;

然后强制转换为(testType*)。

最新更新