memcpy 复制所有数据失败

发布于 2024-09-07 14:08:14 字数 500 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

予囚 2024-09-14 14:08:14

你检查得怎么样了?简单地打印字符串或在调试器中查看它?如果消息中有任何“\0”字符。它将在第一个打印处停止打印。

要查看整个内容,您只需循环并打印每个字符即可。像这样的东西:

int i;
for(i = 0; i < sizeof(wx_msg_buf); ++i) {
   printf("%02x ", wx_msg_buf[i]);
}

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:

int i;
for(i = 0; i < sizeof(wx_msg_buf); ++i) {
   printf("%02x ", wx_msg_buf[i]);
}
秋心╮凉 2024-09-14 14:08:14

该代码对我来说看起来不错。问题可能出在你看待问题的方式上。底层结构的布局是什么?您使用什么工具来观察这 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?

著墨染雨君画夕 2024-09-14 14:08:14

在调试器中检查源数据和结果数据。

几乎不可想象 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.

浅唱々樱花落 2024-09-14 14:08:14

尝试一次; “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

听风念你 2024-09-14 14:08:14

好吧,我将 : 更改

char wx_msg_buf[8192];

char wx_msg_buf[2141];

,现在代码可以工作,但我仍然不明白为什么前面的代码不起作用

Okay, I change :

char wx_msg_buf[8192];

into

char wx_msg_buf[2141];

and now the code work, still I can't understand why the previous won't work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文