C language: Memory placement function memset ()
Simulation Implementation memory placement function memset () We can see from the library function that the function prototype is: void * _ cdecl memset (void * dst, int val, size_t count ), we often use array arr to initialize the back several bytes to 0, but not to set it to other elements, such as 1. This is because: val = 1, is int type, it is assigned to the char type dest, then only the lower eight bits are assigned to the dest, and then the next loop, each time, only one byte of length is assigned to dest. This repeats count times and ends. In the output process, arr is int type, and an int type is four char Types, that is, the output result is: 1000 0000 1000 0000 1000 0000 1000 decimal value. The Code is as follows:
#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>#include<stdlib.h>#include<assert.h>void *my_memset(void *p1, int val, size_t count){ char *dest = (char *)p1; char *ret = dest; while(count--) { *dest = val; dest = dest + 1; } return ret;}int main(){ int arr[] = { 1, 3, 5, 6, 8, 9 }; int i = 0; int *ret = my_memset(arr, 1, 16); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d ", *(ret + i)); } system("pause"); return 0;}