如何memset的初始化-1整数数组? [英] How memset initializes an array of integers by -1?
问题描述
借助手册页说,关于 memset的
:
的#include<&string.h中GT;
无效* memset的(无效* S,INT C,为size_t N)的
memset的()
函数填充第一个N
字节的内存区通过指出为s
随着不断的字节C
。
块引用>显然,
memset的
不能用于初始化INT
阵列,如下图所示:int类型的[10];
memset的(一,1,sizeof的(一));这是因为
INT
重新由4个字节psented(说)$ P $,没有人可以得到在阵列在
。结果
但我经常看到程序员使用memset的
到INT
数组元素设置为0
或1
。int类型的[10];
INT B〔10〕;
memset的(一,0,sizeof的(一));
memset的(二,-1,sizeof的(B));按我的理解,与整数初始化
0
是可以的,因为0
可重新$ P $在psented 1个字节(可能是我错了,在这种情况下)。但怎么可能初始化B
与1
(一个4字节的值)?解决方案奇怪的是,这个工程的原因
1
是完全一样的,这与工作的原因零点:在二进制补码再presentation ,1
的1
S IN的所有位,无论整数的大小,在一个地区做馅用充满了1 <字节/ code>取值产生
1
签署INT
S,长的区域
s和短
S于补硬件。在来自两个互补的不同硬件的结果将是不同的。在
1
整型常量将被转换为unsigned char型
所有的人的,因为标准是具体就如何转换必须执行。然而,与设置为其所有比特字节区域1
将PTED如根据平台的规则积分值间$ P $。例如,标志和硬件级阵列中的所有元素将包含相应类型的最小负值。The manpage says about
memset
:#include <string.h> void *memset(void *s, int c, size_t n)
The
memset()
function fills the firstn
bytes of the memory area pointed to bys
with the constant bytec
.It is obvious that
memset
can't be used to initializeint
array as shown below:int a[10]; memset(a, 1, sizeof(a));
it is because
int
is represented by 4 bytes (say) and one can not get the desired value for the integers in arraya
.
But I often see the programmers usememset
to set theint
array elements to either0
or-1
.int a[10]; int b[10]; memset(a, 0, sizeof(a)); memset(b, -1, sizeof(b));
As per my understanding, initializing with integer
0
is OK because0
can be represented in 1 byte (may be I am wrong in this context). But how is it possible to initializeb
with-1
(a 4 bytes value)?解决方案Oddly, the reason this works with
-1
is exactly the same as the reason that this works with zeros: in two's complement binary representation,-1
has1
s in all its bits, regardless of the size of the integer, so filling in a region with bytes filled with all1
s produces a region of-1
signedint
s,long
s, andshort
s on two's complement hardware.On hardware that differs from two's complement the result will be different. The
-1
integer constant would be converted to anunsigned char
of all ones, because the standard is specific on how the conversion has to be performed. However, a region of bytes with all their bits set to1
would be interpreted as integral values in accordance with the rules of the platform. For example, on sign-and-magnitude hardware all elements of your array would contain the smallest negative value of the corresponding type.这篇关于如何memset的初始化-1整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!