按照內核string.h中函數的順序進行大概的介紹,若干函數會給出一個簡單的例子。有不足之處還但願各位看到的留言告知。c++
1、memcpy:安全
函數原型:extern void * memcpy(void *dest, const void *src, size_t n);函數
函數做用:將從src地址開始的n個字節拷貝到dest開始的地址中。返回值是指向dest的指針。指針
源碼:內存
extern void *memcpy(void *dest, const void *src, size_t n)原型
{源碼
void *ptmp_void = dest;string
size_t tmp_size1, tmp_size2; while
if (!n) {co
return ptmp_void;
}
if ((long)dest & 1) {
char *str_dest = dest;
const char *str_src = src;
*str_dest++ = *str_src;
dest = str_dest;
src = str_src;
n--;
}
if (n > 2 && (long)dest & 2) {
short *s_dest = dest;
const short *s_src = src;
*s_dest++ = *s_src;
dest = s_dest;
src = s_src;
n -= 2;
}
tmp_size1 = n >> 2;
if (tmp_size1) {
long *l_dest = dest;
const long *l_src = src;
for (; tmp_size1; tmp_size1--) {
*l_dest ++ = *l_src;
}
dest = l_dest;
src = l_src;
}
if (n & 2) {
}
if (n & 2) {
short *s_dest =dest;
const short *s_src = src;
*s_dest++ = *s_src++;
dest = s_dest;
src = s_src;
}
if (n & 1) {
char *str_dest = dest;
const char *str_src = src;
*str_dest = *str_src;
}
return ptmp_void;
}
2、memmove:
函數原型:extern void *memmove(void *dest, void *src, size_t n);
函數做用:從src中拷貝n個字節到dest,若是目標區域重合,memmove可以保證源串在被覆蓋以前將重疊區域的字節拷貝到目標區域中。但複製後src內容會被更改。可是當目標區域與源區域沒有重疊則和memcpy函數功能相同。
與memcpy的區別:當拷貝的dest和src有內存區域重合的時候,memmove更大程度的保證正確,而memcpy不能保證必定正確,但不少經常使用狀況是正確的。相比較而言,memmove更爲安全。
源碼:
extern void *memmove(void *dest, const void *src, size_t n)
{
unsigned char *tmp_dest = dest;
const unsigned char *tmp_src = src;
if (dest == src) {
return dest;
}
if (dest < src) {
return memcpy(dest, src, n);
}
while (n -- ) {
tmp_dest[n] = tmp_src[n];
}
return dest;
}
3、memccpy:
函數原型:extern void *memccpy(void *dest, void *src, int c, size_t n);
函數做用:由src所指內存區域複製很少於count個字節到dest所指內存區域,若是遇到字符c則中止複製。返回值表明若是c沒有被複制,則返回NULL,不然,返回字符c 後面緊挨一個字符位置的指針。意思就是隻拷貝src中字符c以前的字符。
4、memset:
函數原型:extern void *memset(void *s, int c, size_t n);
函數做用:對s的前n個字節的每一個字節都設置爲c.
源碼:extern void *memset(void *s, int c, size_t n)
{
int i;
char *ss = s;
for (i = 0; i < n; i++) {
ss[i] = c;
}
return s;
}
5、memcmp:
函數原型:extern int memcmp(const void *s1, const void *s2, size_t n);
函數做用:比較s1和s2中前n個字節。
源碼:extern int memcmp(const void *s1, const void *s2, size_t n)
{
const unsigned char *su1, *su2;
int res = 0;
for(su1 = s1, su2 = s2; 0 < count; ++su1, ++su2, n--) {
if ((res = *su1 - *su2) != 0) {
break;
}
}
return res;
}
6、memchr:
函數原型:extern void *memchr(const void *s1, int c, size_t n);
函數做用:查找s1中的字符c。
源碼:extern void *memchr(const void *s1, int c, size_t n)
{
const unsigned char *p =s;
while(n--) {
if ((unsigned char)c == *p++) {
return (void *)(p - 1);
}
}
return NULL;
}