编译器出错,无法将参数 2 从 MyStruct1 转换为 const void*,用于 memcpy
我正在尝试将数据从一个结构复制到另一个结构。每个结构可以处理的字节是相同的。我的声明和 memcpy 如下:
typedef struct{
CString strNumber;
CString strAlpha;
} _Number;
typedef struct{
CString strIterration;
_Number NumberOne;
_Number NumberTwo;
} _Store;
_Store Data1;
_Store Data2;
现在假设第一个 struct Data1 有数据,第二个刚刚声明。
我正在使用以下代码:
memcpy(&Data2, Data1, sizeof(_Store));
出现错误时无法编译。有什么想法吗?还有其他复制数据的方法吗?
I am trying to copy the data from on structure to another. The bytes are identical that each struct can handle are the same. My declarations and the memcpy are below:
typedef struct{
CString strNumber;
CString strAlpha;
} _Number;
typedef struct{
CString strIterration;
_Number NumberOne;
_Number NumberTwo;
} _Store;
_Store Data1;
_Store Data2;
Now let's say that the first struct Data1 has data and the second is just declared.
I am using the following code:
memcpy(&Data2, Data1, sizeof(_Store));
I cannot compile as the error appears. Any ideas? Any other approaches to copy the data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在两个结构上使用
&
:注意:
_Store
包含CString
成员变量(如果它类似于 MFCCString< /code>) 不可按位复制。您应该只在可按位复制的类型上使用memcpy(),否则您可能会遇到未定义的行为。
You need to use
&
on both structs:Beware:
_Store
containsCString
member variable which (if it is like MFCCString
) is not bitwise copyable. You should only usememcpy()
on types that are bitwise copyable, otherwise you risk running into undefined behavior.显而易见的另一种方法是简单的赋值,即 Data2 = Data1;
这使您不必关心 _Store 结构中有多少字节,也不必关心 CString 是否有运算符 =。
The obvious other approach is simple assignment, i.e., Data2 = Data1;
This saves you from caring how many bytes are in the _Store structure and also from whether CString has an operator =.