strcpy与strncpy学习

包含的头文件:

#include<string.h>

函数原型:

 char *strcpy(char *dest, const char *src);

 char *strncpy(char *dest, const char *src, size_t n);

功能介绍:

1.strcpy函数拷贝字符串指针src所指向的字符串,包括结束符('\0')到dst所指向的目标buffer中,目标字符串dest必须

足够大才能接收拷贝的源字符串,否则,要小心溢出(overruns)的bug。

2.strncpy和strcpy是类似的,除了,它至多拷贝src的n字节数据。

警告:如果在src的前n字节里面结束的空字符('\0'),放在dest的字符串将不会以空字符结尾。

如果src长度小于n,strncpy将会填充空字符到dest字符串,以保证总共n个字节被写入。

strcpy的实现函数:

 1 /***
 2 *char *strcpy(dst, src) - copy one string over another
 3 *
 4 *Purpose:
 5 *       Copies the string src into the spot specified by
 6 *       dest; assumes enough room.
 7 *
 8 *Entry:
 9 *       char * dst - string over which "src" is to be copied
10 *       const char * src - string to be copied over "dst"
11 *
12 *Exit:
13 *       The address of "dst"
14 *
15 *Exceptions:
16 *******************************************************************************/
17 
18 char * strcpy(char * dst, const char * src)
19 {
20         char * cp = dst;
21 
22         while( *cp++ = *src++ )
23                 ;               /* Copy src over dst */
24 
25         return( dst );
26 }

 

一个简单的实现strncpy函数:

 1 char *strncpy(char *dest, const char *src, size_t n)
 2 {
 3     size_t i;
 4     for(i=0;i<n &&src[i] != '\0';i++)
 5         dest[i] = src[i];
 6      for( ; i < n; i++)
 7         dest[i] = '\0';
 8         
 9       return dest;
10 }

返回值:strcpy与strncpy函数都返回目标字符串指针dest。

应用场景:

One valid (and intended) use of strncpy() is to copy a C string to a fixed-length buffer while

ensuring both that the buffer is not overflowed and that unused bytes in the target buffer are 

zeroed out (perhaps to prevent information leaks if the buffer is to be written to media or trans‐

mitted to another process via an interprocess communication technique).

把字符串拷贝到定长的buffer里面,避免溢出并且把目标buffer中未使用的字节初始化为空字符。

关于返回值,返回dest指针是否冗余,因为dest是传入参数?

返回值的作用:是为了增加灵活性,支持链式表达。

 

posted @ 2015-05-13 19:34  general001  阅读(235)  评论(0)    收藏  举报