Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1?
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));
Values 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.
Don't use memset
to initialize anything else than single-byte data types.
At first sight, it might appear that it should work for initializing an int
to 0
or -1
(and on many systems it will work), but then you're not taking into account the possibility that you might generate a trap representation, causing undefined behavior, or the fact that the integer representation is not necessarily two's complement.
The correct way to initialize an array of int
to -1
, is to loop over the array, and set each value explicitly.
gcc provides a good array initialization shortcut
int arr[32] = {[0 ... 10] = 3, [11 ... 31] = 4}
mind the space before and after ...
Why the division?
memset(arr, -1, sizeof(arr));
Your version, sizeof(arr)/sizeof(int)
, gives you the number of elements in the array.
You can save yourself some typing by initializing the array directly:
int arr[5] = {-1, -1, -1, -1, -1};
That line is shorter than the memset, and it also works.
void * memset ( void * ptr, int value, size_t num );
This function works well on most systems when applied to set char array. It sets the first num BYTES of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). memset-C++ Reference It operates one byte each time. So it works fine if you assign the second arguments with a int value no more than 0xff.
As for your version, the third arguments is the number of array elements, so you got your output. Actually the truth is you are supposed to assign the third arguments the NUMBER OF BYTES you want.
So the correct version should be like this:
memset (arr, -1, sizeof(arr));
精彩评论