C language: Memory placement function memset ()

Source: Internet
Author: User

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;}

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.