How memset initializes an array of integers by -1?

后端 未结 2 911
轮回少年
轮回少年 2020-12-13 12:13

The manpage says about memset:

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

The me

2条回答
  •  被撕碎了的回忆
    2020-12-13 12:45

    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.

提交回复
热议问题