为什么" memset的(ARR,-1,的sizeof(ARR)/的sizeof(INT))"不明确的整数数组为-1? [英] Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1?
问题描述
这是不可能的整数数组上使用memset的?我尝试了以下memset的调用和int数组没有得到正确的整数值。
INT ARR [5];
memset的(ARR,-1,的sizeof(ARR)/的sizeof(INT));
Vaules我得到的都是:
改编[0] = -1
改编[1] = 255
ARR [2] = 0
改编[3] = 0
改编[4] = 0
只需更改为 memset的(ARR,-1,的sizeof(ARR));
请注意,不是0值和-1这是行不通自的 memset的设置字节值的记忆开始于由 * PTR
以下指示的可变块 NUM
字节。
的void * memset的(无效* PTR,int值,为size_t NUM);
和自 INT
重新psented在多个字节$ P $,你不会得到你的数组中的整数所需的值。
例外:
- 0是一个例外,因为,如果你设置所有字节为0,该值将为零结果
- -1是因为另一个例外,因为帕特里克强调-1是0xFF的中int8_t(= 255),并为0xffffffff在int32_t
您有其原因:
改编[0] = -1
改编[1] = 255
ARR [2] = 0
改编[3] = 0
改编[4] = 0
是因为,在你的情况,一个int的长度为4个字节(32位重presentation),您的数组的字节长度为20(= 5 * 4),你只设置5个字节为-1(= 255),而不是20。
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));
Vaules I got are:
arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0
Just change to memset (arr, -1, sizeof(arr));
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 );
And since int
is represented on more than one byte, you will not get the desired value for the integers in your array.
Exceptions:
- 0 is an exception since, if you set all the bytes to 0, the value will be zero
- -1 is another exception since, as Patrick highlighted -1 is 0xff (=255) in int8_t and 0xffffffff in int32_t
The reason you got:
arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0
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.
这篇关于为什么" memset的(ARR,-1,的sizeof(ARR)/的sizeof(INT))"不明确的整数数组为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!