具体是这样的,我定义了两个个结构体:
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指针本身的类型没有发生变化
test->input 是
void*。它不能用->。test->input = (B*)(...)会把右侧的B*的指针转换为void*赋值给左侧。C++ 里变量的类型是不能改变的。test->input依然是void*。void*不能使用->。最后一个写法是可以的,因为
tmp1是B*。以上仅讨论编译时的问题。这些写法在运行时几乎都有内存问题。