简体   繁体   English

C中的struct'type cast'错误?

[英]struct 'type cast' error in C?

Suppose I have some struct DATA defined. 假设我定义了一些结构DATA Then I attempt the following code: 然后,我尝试以下代码:

struct DATA data1, data2;
data2 = (DATA)(*(DATA))&data1);

Why do I get error C2440 on 'type cast'? 为什么在“类型转换”中出现错误C2440?

This part is the problem: 这部分是问题:

(DATA)&data1

Here you takes the address of data1 making into a pointer, type struct DATA * . 在这里,您将data1的地址作为指针,键入struct DATA * Then you try to cast it to a non-pointer struct DATA type which is what the error is probably about. 然后,您尝试将其强制转换为非指针struct DATA类型,这可能是该错误的原因。 (Hint: Please post complete and unedited error messages in the future.) (提示:请在将来发布完整且未经编辑的错误消息。)

You actually don't have to do any casting, or address-of pointer handling or dereferencing at all. 实际上,您根本不需要进行任何强制转换,指针地址处理或取消引用。 Just assign one structure to the other, and the compiler will create code to do the proper copying: 只需将一个结构分配给另一个结构,编译器将创建代码以进行正确的复制:

data2 = data1;

The right thing to do is : 正确的做法是:

struct DATA data1, data2;
data2 = (struct DATA)(*((struct DATA*)&data1));

But this is useless... What not doing this : 但这是没有用的...不这样做是什么:

struct DATA data1, data2;
data2 = data1;

It's illegal to cast to a struct type. 强制转换为结构类型是非法的。 The type specified by a cast operator must be either void or a scalar type (ie, an arithmetic or pointer type). 强制转换运算符指定的类型必须为void或标量类型(即算术或指针类型)。

This: 这个:

data2 = data1;

is a much simpler way to do what I think you're trying to do (it's hard to tell). 是我认为您要尝试做的事情的一种简单得多的方法(这很难说)。

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

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