Thursday, 11 December 2014

memset( ) function in C++

Today I learnt that I always misinterpreted the working of memset( ) in C++.
I generally use memset( ) to set integer arrays as either 0 or infinity (some very large integer), but sometimes I need to set it to other values as well.

Consider an array :
int a[100];

My understanding was that calling memset(a,127,sizeof(a)); would set all elements in the array as 127.

However, this is not how memset( ) works.

memset( ) writes byte-wise on the memory.
Calling memset(a,127,sizeof(a)) sets every byte, in every integer, as 127.

So, the actual value that will be assigned to each integer in the array a[ ] would be a much larger integer value.

From :
void * memset ( void * ptr, int value, size_t num );

Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).