strcpy vs memcpy
【本文连接】
http://www.cnblogs.com/hellogiser/p/strcpy_vs_memcpy.html
【分析】
strcpy和memcpy都是标准C库函数,它们有下面的特点。 strcpy提供了字符串的复制。即strcpy只用于字符串复制,并且它不仅复制字符串内容之外,还会复制字符串的结束符。
已知strcpy函数的原型是
C++ Code
1
|
char *strcpy(char *dest, const char *src);
|
memcpy提供了一般内存的复制。即memcpy对于需要复制的内容没有限制,因此用途更广。
C++ Code
1
|
void *memcpy( void *dest, const void *src, size_t count );
|
strcpy和memcpy主要有以下3方面的区别。
1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
#include <stdio.h>
#include <stdlib.h> #include <string.h> #include <iostream> using namespace std; /* * copy strings by \0 * (1) not check overlapping * (2) dest mush have enough space to contain the same C string as src including the \0 * */ char *my_strcpy(char *dest, const char *src) { if(src == NULL || dest == NULL) return NULL; char *d = dest; const char *s = src; while((*d++ = *s++) != '\0') // notice here ; return dest; /* support chaining * int len = strlen(my_strcpy(dest,src)); * */ } /* * not check overlapping * optimization: copy by word(4 or 8 bytes) instead of by 1 byte * */ void *my_memcpy(void *dest, const void *src, size_t count) { if(src == NULL || dest == NULL) return NULL; char *d = (char *)dest; const char *s = (const char *)src; while(count--) { *d ++ = *s ++; } return dest; } /* * check overlapping * optimization: copy by word(4 or 8 bytes) instead of by 1 byte * */ /* * d == s * d <s, copying from the beginning * d >s, copying from the end * */ void *my_memmove(void *dest, const void *src, size_t count) { if(src == NULL || dest == NULL) return NULL; char *d = (char *)dest; const char *s = (const char *)src; if(d < s) { //copy from the beginning while(count--) { *d++ = *s++; } } else if(d > s) { //copy from the end d = d + count - 1; s = s + count - 1; while(count--) { *d-- = *s--; } } else { // do nothing } return dest; } void test_case() { char str1[] = "sample string"; char str2[40]; char str3[40]; my_strcpy(str2, str1); my_strcpy(str3, "copy successful"); printf("str1: %s\nstr2: %s\nstr3: %s\n", str1, str2, str3); } void test_case2() { char dest[100]; const char *src = "hello"; my_memcpy(dest, src, strlen(src) + 1); printf("%s\n", dest); } int main() { test_case(); test_case2(); return 0; } |
【参考】
http://www.cnblogs.com/stoneJin/archive/2011/09/16/2179248.html
http://www.cplusplus.com/reference/cstring/strcpy/