为什么memset的()不正确初始化INT?

编程入门 行业动态 更新时间:2024-10-26 01:33:09
本文介绍了为什么memset的()不正确初始化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?

本文发布于:2023-11-10 06:08:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   不正确   memset   INT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!