# 标准库函数实现

478人阅读 评论(0)

1、memcpy

void *memcpy(void *dst, const void *src, size_t n);
//If copying takes place between objects that overlap, the behavior is undefined.

void* memcpy(void *dst, const void *src, size_t count)
{
//安全检查
assert( (dst != NULL) && (src != NULL) );

char *pdst = (char *)dst;
const char *psrc = (const char *)src;

//防止内存重复
assert(!(psrc<=pdst && pdst<psrc+count));
assert(!(pdst<=psrc && psrc<pdst+count));

while(count--)
{
*pdst++ = *psrc++;
}
return dst;
}    

2、strcpy

char * strcpy( char *dest, const char *src )
{
assert( (dest != NULL) && (src != NULL) );
if(dest == src)
return dest;

char *ptr = dest;
while( (*dest++ = * src++) != '\0' )
;
return ptr;
}  

3、strncpy

char *strncpy(char *dest, const char *src, size_t count)
{
assert(dest != NULL && src != NULL);
char *ptr = dest;
while (count-- && *src != '\0')
*dest++ = *src++;
*dest = '\0';
return ptr;
} 

4、strstr

char *strStr(char *haystack, char *needle)
{
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(needle == NULL || haystack == NULL)
return NULL;
int i,j;
for (i = j = 0; haystack[i] && needle[j];)
{
if (haystack[i] == needle[j])
{
++i;
++j;
}
else
{
i = i - j + 1;
j = 0;
}
}
return needle[j]?NULL:(haystack + i - j);

}


5、memmove

void* memmove(void* dst,const void* src,size_t n)
{
assert(dst != NULL && src != NULL);
char* p = (char*)dst;
char* q = (char*)src;

if (p <= q || p >= q + n)//
{
while (n--)
{
*p++ = *q++; //按递增拷贝
}
}
else  //
{
p += n -1;//overlap的情况，从高位地址向低位拷贝
q += n -1;
while (n--)
{
*p-- = *q--; //按递减拷贝
}
}
return dst;
}

6、strcmp

int strcmp(const char *s, const char *t)
{
assert(s != NULL && t != NULL);
while (*s && *t && *s == *t)
{
++ s;
++ t;
}
return (*s - *t);
}     

7、strlen

size_t strlen(const char *str)
{
assert(str != NULL);

const char *s = str;
while(*s != '\0')
s++;
return(s - str);
}

8、strcat

char *strcat(char *dst, const char *src)
{
assert((dst != NULL) && (src != NULL));

char *pdst = dst;
while (*dst != '\0')
++dst;
while ((*dst++ = *src++) != '\0')
;
return pdst;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：136206次
• 积分：2779
• 等级：
• 排名：第12923名
• 原创：134篇
• 转载：106篇
• 译文：1篇
• 评论：6条
阅读排行
评论排行