memcpy 复制所有数据失败
我在 C 中遇到了 memcpy 的问题。这是代码:
typedef struct {
CPY_IM009_DEF
}message;
message msg;
CPY_IM009_DEF 是其他文件中的结构。 我尝试这样做
char wx_msg_buf[8192];
memset(wx_msg_buf, 32, sizeof (wx_msg_buf));
memcpy(wx_msg_buf, &msg, sizeof (msg));
然后,当我检查大小时,
: sizeof (msg) = 2140
sizeof (wx_msg_buf) = 8192
但是当我检查 wx_msg_buf 时,memcpy 仅将部分 msg 复制到 wx_msg_buf (从 2140 到 200)。 我想知道为什么会发生这种情况?如果需要更多代码,请告诉我,
谢谢您的帮助。
I encounter problem with memcpy in C. Here is the code :
typedef struct {
CPY_IM009_DEF
}message;
message msg;
with CPY_IM009_DEF is a struct in other files. Then I try this
char wx_msg_buf[8192];
memset(wx_msg_buf, 32, sizeof (wx_msg_buf));
memcpy(wx_msg_buf, &msg, sizeof (msg));
when I check the size :
sizeof (msg) = 2140
sizeof (wx_msg_buf) = 8192
But when I check the wx_msg_buf, memcpy only copy part of msg to wx_msg_buf (200 from 2140).
What I want to know is why does this happen?If more code required please tell me
Thanx you for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你检查得怎么样了?简单地打印字符串或在调试器中查看它?如果消息中有任何“\0”字符。它将在第一个打印处停止打印。
要查看整个内容,您只需循环并打印每个字符即可。像这样的东西:
How are you checking? Simply printing the string or looking at it in a debugger? If the message has any '\0' characters in it. It will stop printing at the first one.
To see the whole thing, you can just loop through and print each character. Something like this:
该代码对我来说看起来不错。问题可能出在你看待问题的方式上。底层结构的布局是什么?您使用什么工具来观察这 2000 字节?
The code looks fine to me. The problem may be with the way you look at it. What is the layout of the underlying structure, and what tools to you use to get the observation about the 2000 bytes?
在调试器中检查源数据和结果数据。
几乎不可想象 memcpy() 有一个缺陷,它的使用如此广泛。
Check your source data and your result data in a debugger.
It is almost inconceivable that memcpy() has a defect, it's used so widely.
尝试一次; “memmove”而不是“memcpy”..
memcpy() 速度更快,但移动源和目标重叠的内存块并不安全。在这些情况下,可以使用 memmove() 来移动内存。
所以最好使用“memmove”..我认为它会解决你的问题
Try once; "memmove" instead of "memcpy"..
memcpy() is faster, but it's not safe for moving blocks of memory where the source and destination overlap. memmove() can be used to move memory in those cases.
So better use "memmove".. i think it will solve your problem
好吧,我将 : 更改
为
,现在代码可以工作,但我仍然不明白为什么前面的代码不起作用
Okay, I change :
into
and now the code work, still I can't understand why the previous won't work