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:
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.