Using memset for integer array in C
char str[] = "beautiful earth";
memset(str, '*', 6);
printf("%s", str);
Output:
******ful earth
Like the above use of memset, can we initialize only a few integer array index values to 1 as given below?
int arr[15];
memset(arr, 1, 6);
No, you cannot use memset()
like this. The manpage says (emphasis mine):
The
memset()
function fills the firstn
bytes of the memory area pointed to bys
with the constant bytec
.
Since an int
is usually 4 bytes, this won't cut it.
If you (incorrectly!!) try to do this:
int arr[15];
memset(arr, 1, 6*sizeof(int)); //wrong!
then the first 6 int
s in the array will actually be set to 0x01010101 = 16843009.
The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is memset(thing, 0, sizeof(thing));
to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.
The solution is to use a for
loop and set it yourself:
int arr[15];
int i;
for (i=0; i<6; ++i) // Set the first 6 elements in the array
arr[i] = 1; // to the value 1.
Short answer, NO.
Long answer, memset
sets bytes and works for characters because they are single bytes, but integers are not.
On Linux, OSX and other UNIX like operating systems where wchar_t
is 32 bits and you can use wmemset()
instead of memset()
.
#include<wchar.h>
...
int arr[15];
wmemset( arr, 1, 6 );
Note that wchar_t
on MS-Windows is 16 bits so this trick may not work.