cfunction in practics

what’s functin memset(score,0,sizeof score). what do it.

Refer http://www.cplusplus.com/reference/cstring/memset/ for some official details on memset.

The call memset(ptr, value, n) sets the first n Bytes of memory to value, starting at the address pointed to by ptr.

So, memset(score, 0, sizeof(score)) fills an array called score (assuming score is declared as an array. If score is declared as a pointer and proper malloc or new is done, it will work just the same) completely with 0. You can note that the data to be written is 0 and the number of bytes is sizeof(score), which is the whole array (or the memory allocated at runtime, whichever is applicable).

Hope this helps!

the signature of the function is void * memset (void * FromPtr, int Value, size_t NumBytes );

starting from the memory location “FromPtr”, set the next “NumBytes” with the ‘byte’ representation of “Value”.

by ‘byte’ representation it means binary representation of the number truncated to 8 least significant bits. so, it means that Value = 0 and Value = 256 will initialize the memories in similar fashion.

for example,

int a[5];
memset(a, 0, 5 * sizeof(int));

after this initialization, the binary representation of each member of a will be 000…(32 bits)

whereas

memset(a, 15, 5 * sizeof(int));

will initialize each member to ‘00001111 00001111 00001111 00001111’. This is definitely not 15! So, if you are expecting to initialize each member with 15, better run through a loop!

1 Like