【问题标题】:How do i cast a void pointer to struct type?如何将 void 指针转换为结构类型?
【发布时间】:2023-02-26 00:09:05
【问题描述】:

所以我想知道如何将 void 指针类型转换为结构类型。

代码-

#include <stdio.h>

struct man
{
    int age;
    int var;
};

struct woman
{
    char c;
    int age;
    int var;
};

void * ptr;

struct man mlist[2];
struct woman wlist[2];

struct man * mptr=mlist;    //mptr points to first element of mlist
struct woman *wptr=wlist;

int function(int gender,int a,int b)   ///a,b are for struct
{
    
    if(gender==1)
    {
        (struct man *)ptr=mptr;
       // ptr=(struct man *)ptr;
       //ptr=(struct man *)mptr;

    }
    else
    {
        (struct woman *)ptr=wptr;
          //ptr=(struct woman *)ptr;
    }
    ptr->age=a;      //dont know if man or woman
    ptr->var=b;     
    
    return (ptr->age+ptr->var);   
    
}

void main(void) 
{
    printf("\n%d\n",function(1,10,3));
}

我收到错误消息 error: request for member 'age' in something not a structure or union error: request for member 'var' in something not a structure or union 以及警告 warning: dereferencing 'void *' pointer 38 | ptr-&gt;var=b;

我尝试了几种类型转换 void 指针 *ptr 的方法,但无济于事。我想以这种方式解决这个问题,因为这是一个更大程序的原型。

如果有一些我可能遗漏的概念,请随时纠正我,我对编程还比较陌生。

我试图以这种方式输入 cast :

ptr=(struct man *)mptr; (struct man *)ptr=mptr; ptr=mptr; ptr=(struct man*)ptr;

但错误仍然存​​在。

【问题讨论】:

  • 通常 function 会接受 void* 并将其解释为 struct man *struct woman * 取决于 int gender,然后根据它做事。如果这是为了上课,你应该和你的教职员工谈谈。
  • ((struct man *)ptr)->年龄

标签: c pointers casting structure


【解决方案1】:

用你的结构是不可能的。结构内部变量的偏移量是不同的,你不能有一个可以指向任何一个结构的通用指针。

相反,我建议您创建一个由您的两个结构使用的公共结构,该结构放在两个结构的第一位。它将模拟面向对象语言中的继承。

所以改为例如

struct common_data
{
    unsigned age;  // Unsigned, since age can't be negative
    int var;
};

struct man
{
    struct common_data common;
};

struct woman
{
    struct common_data common;
    char c;
};

现在您可以使用指向任一结构的指针作为指向公共结构的指针:

struct common_data *common;

if (gender == 1)
{
    common = (struct common_data *) mptr;
}
else
{
    common = (struct common_data *) wptr;
}

common->age = a;
common->var = b;

【讨论】:

  • 建议:common = &amp;mptr-&gt;common;
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2021-09-20
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
相关资源
最近更新 更多