rambo

C++面试语法糖(四)

1、strcpy与memcpy的区别

strcpy和memcpy都是标准C库函数,它们有下面的特点。

  • strcpy提供了字符串的复制。即strcpy只用于字符串复制,并且它不仅复制字符串内容之外,还会复制字符串的结束符。
  • memcpy提供了一般内存的复制。即memcpy对于需要复制的内容没有限制,因此用途更广。

Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string assource (including the terminating null character), and should not overlap in memory with source

说明:strcpy函数返回char *类型的原因是为了能使用链式表达式。首先调用mystrcpy使得strDest指针复制strSrc的内存数据,然后调用strl函数获取strDest字符串的长度。

对于栈来讲,它的生长方向是向下的,是向着内存地址减小的方向增长。(定义一个栈底--这是高地址,每次压一个数据入栈,栈指针esp减去4(32位系统下),所以栈顶是向着内存低地址方向生长的。)戳本文

 

The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
The function does not check for any terminating null character in source - it always copies exactly num bytes.

To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least numbytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).

总结:

复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
复制的方法不同。strcpy不需要指定长度,它遇到字符串结束符"\0"便结束。memcpy则是根据其第3个参数决定复制的长度。
用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy。

最大的差别是性能, memcpy按块拷贝, strcpy按字节.(待考证)

一个memcpy的结构体的复制,类似于C++中调用类的拷贝构造函数,用一个对象去初始化另一个对象。

测试结果:time_b始终保持为0,time_a随SIZE的增大不断增加。
memcpy比直接赋值更快?是因为在堆上原因多一些I/O么?

http://blog.const.net.cn/a/9237.htm

http://bbs.csdn.net/topics/390233140