为什么memset的()不正确初始化INT? [英] Why is memset() incorrectly initializing int?
问题描述
为什么以下程序的输出 84215045
?
INT电网[110];
诠释的main()
{
memset的(网格,5,100 * sizeof的(INT));
的printf(%d个网格[0]);
返回0;
}
memset的
设置每个目标缓冲区到指定值的字节。在您的系统, INT
是四个字节,每个调用 memset的
后是5。因此,电网[0]
值为 0x05050505
(十六进制),这是 84215045
十进制。
一些平台提供可供选择的API来 memset的
的写更宽模式的目标缓冲区;例如,在OS X或iOS,你可以使用:
INT模式= 5;
memset_pattern4(网格和放大器;格局,sizeof的网格);
让你似乎期望的行为。你瞄准什么平台?
在C ++中,你应该只使用的std :: fill_n
:
的std :: fill_n(网格,100,5);
Why is the output of the following program 84215045
?
int grid[110];
int main()
{
memset(grid, 5, 100 * sizeof(int));
printf("%d", grid[0]);
return 0;
}
memset
sets each byte of the destination buffer to the specified value. On your system, an int
is four bytes, each of which is 5 after the call to memset
. Thus, grid[0]
has the value 0x05050505
(hexadecimal), which is 84215045
in decimal.
Some platforms provide alternative APIs to memset
that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:
int pattern = 5;
memset_pattern4(grid, &pattern, sizeof grid);
to get the behavior that you seem to expect. What platform are you targeting?
In C++, you should just use std::fill_n
:
std::fill_n(grid, 100, 5);
这篇关于为什么memset的()不正确初始化INT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!