结构体嵌套情况下,C语言void*类型赋值失败?

具体是这样的,我定义了两个个结构体:

typedef struct
{
    void* input;
    void* output;
} A;

typedef struct
{
    char* data1;
    int* data2;
} B;

在使用的时候做了如下操作

A* test;
test->input = (B*)(test->input);
test->output = (B*)(test->output);

test->input->data1 = "hello";
*(test->input->data2) = 1;

换了另一种写法也是报错

A* test;
B* tmp1 = NULL;
test->input = tmp1;

test->input->data1 = "hello";

其中最后两句给data1和data2赋值的语句编译报错(ubuntu上的gcc),报错说data1、data2 in something not a struct or union
改成下列语句后编译通过了

A* test;
B* tmp1;

tmp1->data1 = "hello";
*(tmp1->data2) = 1;

test->input = tmp1;

想问为什么第一种写法不会通过?
另外想问下面这个写法能够通过编译吗?

A* test;
B* tmp1 = (B*)(test->input);
tmp1->data1 = "hello";

已解决:
将其它类型的指针赋给void指针后,虽然可以赋值,但void指针本身的类型没有发生变化

阅读 2k
2 个回答

test->input 是 void* 。它不能用 ->

test->input = (B*)(...) 会把右侧的 B* 的指针转换为 void* 赋值给左侧。C++ 里变量的类型是不能改变的。test->input 依然是 void*void* 不能使用 ->

最后一个写法是可以的,因为 tmp1B*


以上仅讨论编译时的问题。这些写法在运行时几乎都有内存问题。

A* test = (A*)malloc(sizeof(A));
B* tmp1 = (B*)malloc(sizeof(B));
tmp1->data1 = "hello";
tmp1->data2 = (int*)malloc(sizeof(int));
*(tmp1->data2) = 1;
test->input = tmp1;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题