问题描述
我有一个如下数组 -
char arr [100];
现在我希望将以下int -
int tmp = 0x01020304;
复制到此数组中,在元素[12 ]。
以下内容会有相同的结果 -
ThePacket3 [12] = 1;
ThePacket3 [13] = 2;
ThePacket3 [14] = 3;
ThePacket3 [15] = 4;
怎么能我这样做没有将我的int分成4个字节并逐个分配
每个元素?
谢谢,
Barry。
写一个函数或宏。 />
它被称为模块化设计。而不是复制/粘贴你在snippets.org上找到的相同的
代码片段,你实际上是从一个设计中构建了一个程序
,你将常见的功能抽象到一个体,
几乎是一个图书馆如果你愿意,你的应用程序的支持代码或
项目。
Tom
您可以尝试这样做:
memcpy(& arr [12],& tmp,sizeof(int));
只要确保你确切知道自己在做什么。例如int
不需要4字节长。
-
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org(希望现在还不算太晚)
(......它还能运作......)
你不能,便携。
1.特定机器的字节顺序可能会导致将字节分配给不同于上面列出的字符的
。
2 。[element] [12]可能没有正确的int对齐方式,导致崩溃。
3. sizeof(int)可能不是4,导致数组的元素超过4个
可以修改ed。
这就是为什么人们写宏(按特定顺序分配字节)
满足这些需求。
S
-
Stephen Sprunk愚蠢的人用智能环绕自己
CCIE#3723人。聪明的人围绕着他们自己与他们不同意的K5SSS聪明人。 --Aaron Sorkin
-
通过
Hi,
I have an array as follows -
char arr[100];
Now I wish to copy the following int -
int tmp = 0x01020304;
into this array, at element[12].
This following would have the same result -
ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;
How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?
Thanks,
Barry.
Write a function or macro.
It''s called "modular design" where instead of copy/pasting the same
code snippet you found on snippets.org you actually build up a program
from a design where you abstract out common functionality to a body,
almost a "library" if you will, of support code for your application or
project.
Tom
You could probably try this:
memcpy(&arr[12],&tmp,sizeof(int));
Just make sure you know exactly what you''re doing. For example int
doesn''t need to be 4 byte long.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it''s not too late)
(... and that it still works...)
You can''t, portably.
1. The endianness of a particular machine may cause the bytes to be assigned
to different chars than what you''ve listed above.
2. element[12] may not have proper alignment for an int, causing a crash.
3. sizeof(int) may not be 4, causing more than 4 elements of your array to
be modified.
This is why folks write macros (which assign the bytes in a specific order)
for such needs.
S
--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
--
Posted via a free Usenet account from http://www.teranews.com
这篇关于将4字节块复制到char数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!