memset 如何用 -1 初始化整数数组? [英] How memset initializes an array of integers by -1?

查看:26
本文介绍了memset 如何用 -1 初始化整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

手册页介绍了memset:

<块引用>

#include void *memset(void *s, int c, size_t n)

memset() 函数用 s 指向的内存区域的前 n bytes 填充常量字节 c.

很明显,memset不能用于初始化int数组,如下图:

int a[10];memset(a, 1, sizeof(a));

这是因为int由4个字节表示(比如说),并且无法获得数组a中整数的所需值.
但我经常看到程序员使用memsetint 数组元素设置为0-1.

int a[10];int b[10];memset(a, 0, sizeof(a));memset(b, -1, sizeof(b));

根据我的理解,用整数 0 初始化是可以的,因为 0 可以用 1 个字节表示(可能是我在这种情况下错了).但是如何用 -1 (一个 4 字节的值)来初始化 b 呢?

解决方案

奇怪的是,这适用于 -1 的原因与适用于零的原因完全相同:在 二进制补码-11s 在它的所有位中,不管整数的大小,所以用所有 1 填充的字节填充一个区域会产生一个 -1 签名的 区域二进制补码硬件上的 >ints、longs 和 shorts.

在不同于二进制补码的硬件上,结果会有所不同.-1 整型常量将被转换为所有 1 的 unsigned char,因为标准是特定于如何执行转换的.但是,根据平台规则,所有位都设置为 1 的字节区域将被解释为整数值.例如,在符号和大小硬件上,数组的所有元素都将包含相应类型的最小负值.

The manpage says about memset:

#include <string.h>
void *memset(void *s, int c, size_t n)

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

It is obvious that memset can't be used to initialize int 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 array a.
But I often see the programmers use memset to set the int array elements to either 0 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 because 0 can be represented in 1 byte (may be I am wrong in this context). But how is it possible to initialize b 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 has 1s in all its bits, regardless of the size of the integer, so filling in a region with bytes filled with all 1s produces a region of -1 signed ints, longs, and shorts 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 an unsigned 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 to 1 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆