为什么“memset(arr, -1, sizeof(arr)/sizeof(int))"未将整数数组清除为 -1?
不能在整数数组上使用 memset
吗?我尝试了以下 memset
调用,但没有在 int
数组中获得正确的整数值.
Is it not possible to use memset
on an array of integers? I tried the following memset
call and didn't get the correct integer values in the int
array.
int arr[5];
memset (arr, -1, sizeof(arr)/sizeof(int));
我得到的值是:
arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0
只需更改为 memset (arr, -1, sizeof(arr));
请注意,对于 0 和 -1 以外的其他值,这将不起作用,因为 memset 为从 *ptr
指示的变量开始的内存块设置字节值,用于以下 num
字节.
Note that for other values than 0 and -1 this would not work since memset sets the byte values for the block of memory that starts at the variable indicated by *ptr
for the following num
bytes.
void * memset ( void * ptr, int value, size_t num );
而且由于 int
以多个字节表示,因此您将无法获得数组中整数的所需值.
And since int
is represented on more than one byte, you will not get the desired value for the integers in your array.
例外:
- 0 是一个例外,因为如果您将所有字节设置为 0,则该值将为零
- -1 是另一个例外,因为帕特里克强调 -1 在 int8_t 中是 0xff (=255),在 int32_t 中是 0xffffffff
你得到的原因:
arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0
是因为,在您的情况下,int 的长度为 4 个字节(32 位表示),您的数组长度(以字节为单位)为 20(=5*4),而您只将 5 个字节设置为 -1(=255) 而不是 20.
Is because, in your case, the length of an int is 4 bytes (32 bit representation), the length of your array in bytes being 20 (=5*4), and you only set 5 bytes to -1 (=255) instead of 20.