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

查看:924
本文介绍了如何memset的初始化-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 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天全站免登陆