初始化用memset的整个数组 [英] Initializing entire array with memset
问题描述
我已经初始化整个数组值为1,但输出正显示出一些垃圾值。但此方案正常工作,如果我在的地方1.使用0或-1那么,有没有什么类型的值可以用memset进行初始化一些限制。
INT的main(){
诠释[100];
memset的(一,1,sizeof的(一));
COUT&所述;&下;一个[5]&下;&下; ENDL;
返回0;
}
memset的,因为其他说,在指定的值数组中的每个字节集。
这适用于0和-1的原因是因为两者使用相同的重复图案任意大小:
(INT)-1为0xffffffff
(炭)-1为0xFF
所以填充内存区域0xFF的
将有效填补了数组-1。
不过,如果你使用 1
加油吧,你的每一个字节到 0×01
设置;因此,这将是一样的每个整数的值设置为 0x01010101
,这是不太可能你想要什么。
I have initialised the entire array with value 1 but the output is showing some garbage value. But this program works correctly if i use 0 or -1 in place of 1. So are there some restrictions on what type of values can be initialised using memset.
int main(){
int a[100];
memset(a,1,sizeof(a));
cout<<a[5]<<endl;
return 0;
}
memset, as the other say, sets every byte of the array at the specified value.
The reason this works with 0 and -1 is because both use the same repeating pattern on arbitrary sizes:
(int) -1 is 0xffffffff
(char) -1 is 0xff
so filling a memory region with 0xff
will effectively fill the array with -1.
However, if you're filling it with 1
, you are setting every byte to 0x01
; hence, it would be the same as setting every integer to the value 0x01010101
, which is very unlikely what you want.
这篇关于初始化用memset的整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!