问:如下代码分别用strncpy和snprintf拷贝字符串,都能符合预期吗?
#include <stdio.h>
#include <stdint.h>
#include <string.h>
char *pch = "hello word";
int main(int argc, char* argv[])
{
char buf1[32];
char buf2[32];
memset(buf1, '*', sizeof(buf1));
memset(buf2, '*', sizeof(buf2));
strncpy(buf1, pch, 5);
snprintf(buf2, 5, "%s", pch);
printf("buf1:%s\r\n", buf1);
printf("buf2:%s\r\n", buf2);
return 0;
}
答:运行输出如下:
buf1:hello***************************hell
buf2:hell
问:strncpy拷贝5个字符,为什么后面多出来那么多字符?snprintf拷贝5个字符,为什么只输出4个字符?
答:char *strncpy(char *dest, const char *src, int n),当src的长度大于或等于n时如实拷贝n个字符,dest的尾部不会自动添加空字符;int snprintf(char* dest, size_t size, const char* format, ...),当格式化字符串的长度大于或等于n时,只会复制n-1个字符到dest,结尾自动添加空字符。
总结:字符串处理函数一般都会在结尾自动添加空字符,只有strncpy是个特例,当src的长度大于或等于n时,dest的尾部不会自动添加空字符,当src的长度小于n时才会自动添加空字符。