- strcpy 和 strncpy
先看看man手册里对strcpy和strncpy的说明:
The strcpy() function copies the string pointed to by src, including
the terminating null byte (‘\0’), to the buffer pointed to by dest.
The strings may not overlap, and the destination string dest must be
large enough to receive the copy.strcpy在进行字符串拷贝的时候,会把src中的’\0’也拷贝进dest中。要求src和dest在内存上不重叠,而且dest的内存空间要大于src,以防止内存溢出。
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated. If the length of src is less than n, strncpy() pads the remainder of dest with null bytes.
strncpy跟strcpy函数类似,区别在只拷贝了src中n个字节到dest中。需要注意的是:如果前n个字符串后面没有’\0’的话,dest中将不会有终止符。
好了 我们来做两个实验来说明这个(以下代码都在ubuntu12.04 + gcc 4.6.3环境下):
#include <stdio.h>
#include <string.h>
int main(void)
{
char len = 0;
char dest[20];
char src[11];
sprintf(src,"%s","hello,world");
strcpy(dest,src);
len = strlen(dest);
printf("%d\n",len);
printf("%s\n",dest);
return 0;
}
/*
Output:
11
hello,world
*/
//这个结果是我们预期的结果
//接下来是strncpy
#include <stdio.h>
#include <string.h>
int main(void)
{
char len = 0;
char dest[20];
char src[11];
strcpy(src,"hello,world");
strncpy(dest,src,5); //这次我们只将src中5个字符拷贝进dest中
len = strlen(dest);
printf("%d\n",len);
printf("%s\n",dest);
return 0;
}
/*
Output:
31
hello���}^���u�U~^��hello,world
*/
//BS,这个结果~
//根据man手册里的描述,那么在这种情况下,就需要手动给dest[5] = '\0' 进行这样的赋
//值操作,这样输出就正常了~
/*
Output:
5
hello
*/
在man手册里,关于strncpy还有这样一句话:
If the length of src is less than n, strncpy() pads the remainder of
dest with null bytes.
如果src的长度比参数n小的话,将会自动的在dest后面添加一个终止符。
这个是可行的。比如将上述例子中,n值赋值为13 ( n > strlen(src) ),程序将会输出如下:
/*
Output:
11
hello,world
*/
但是也只适用于要全部拷贝的情况下。
在Tutorialspoint给的例子中,首先将dest用memset进行了初始化操作,道理都是一样的,具体怎么用,还是看个人爱好。
总结:国外论坛上有很多关于strcpy和strncpy的谩骂声,比较抵制这两种方法,没有error机制,需要浪费时间填写终止符,需要时刻注意是否溢出~
sprintf和snprintf
memcpy 和 memmove