原型: void *memset(void *buffer, int c, int count);
用法:#include <string.h>
功能:把buffer所指内存区域的前count个字节设置成字符c。
说明:返回指向buffer的指针。
源码实现:
void *memset(void *src, int c, size_t count)
{
assert(src!=NULL);
char *tmpsrc=(char*)src;
while(count--)
*tmpsrc++ =(char)c;
return src;
}
实现1:《高质量c++,c编程指南》
[cpp] view plain copy
- void *mymemcpy(void *dst,const void *src,size_t num)
- {
- assert((dst!=NULL)&&(src!=NULL));
- //assert(des>=src+num||src>dst+num);
- byte * psrc = (byte *)src;//byte 既为unsigned char类型
- byte * pdst = (byte *)dst;
- while(num-->0)*pdst++ = *psrc++;
- return dst;
- }
缺点:没有考虑内存重叠的情况,可以加一个断言换为:assert(des>=src+num||src>dst+num);
实现2:考虑重叠,有重叠情况也复制
[cpp] view plain copy
- void * mymemcpy(void *dest, const void *src, size_t count)
- {
- if (dest == NULL || src == NULL)
- return NULL;
- char *pdest = static_cast <char*>(dest);
- const char *psrc = static_cast <const char*>(psrc);
- int n = count;
- if (pdest > psrc && pdest < psrc+count)
- {
- for (size_t i=n-1; i != -1; --i)
- {
- pdest[i] = psrc[i];
- }
- }
- else
- {
- for (size_t i= 0; i < n; i++)
- {
- pdest[i] = psrc[i];
- }
- }
- return dest;
- }