字符数组就是元素为字符变量的数组
而字符串则是以'\0'为结束字符的字符数组.可见字符数组并不一定是字符串
如果用一个字符串字面常量来初始化一个字符数组,数组的长度至少要比字符串字面常量的长度大1,因为还要保存结束符'\0'.例如:
char array[] = "Hello";
数组array的元素为{'H','e','l','l','o','\0'}.
char arrChar_1[] = {'z','h','\0','m','e'};
char arrChar_2[] = "Hello";
char *p = "hello";
cout<<sizeof(arrChar_1)<<endl; // 5,数组占5byte
cout<<strlen(arrChar_1)<<endl; // 2,字符串长度为2
cout<<sizeof(arrChar_2)<<endl; // 6,数组占6byte
cout<<strlen(arrChar_2)<<endl; // 5,字符串长度为5
cout<<sizeof(p)<<endl; // 4,指针p占4byte
cout<<strlen(p)<<endl; // 5,字符串长度为5
在 ANSI C 中,strcpy 的安全版本是 strncpy。
char *strncpy(char *s1, const char *s2, size_t n);
但 strncpy 其行为是很诡异的(不符合我们的通常习惯)。标准规定 n 并不是 sizeof(s1),就是 strncpy 并不帮你保证 \0
结束。
char buf[8];
strncpy( buf, "abcdefgh", 8 );
看这个程序,buf 将会被 "abcdefgh" 填满,但却没有 \0 结束符了。
另外,如果 s2 的内容比较少,而 n 又比较大的话,strncpy 将会把之间的空间都用 \0 填充。这又出现了一个效率上的问题,如下:
char buf[80];
strncpy( buf, "abcdefgh", 79 );
上面的 strncpy 会填写 79 个 char,而不仅仅是 "abcdefgh" 本身。
strncpy 的标准用法为:(手工写上 \0)
strncpy(path, src,sizeof(path) - 1);
path[sizeof(path) - 1] = '\0';
len = strlen(path);
char* strncpy(char* dest, const char* src, int len)
{
assert(dest!=NULL && src!=NULL);
char* temp=dest;
int i=0;
while(i++ < len && (*temp++ = *src++)!='\0') {}
/*
if(*(--temp)!='\0')
*temp='\0';
*/
return dest;
}