C语言中string注意事项

在C中,string可以用char 类型的数组来表示,要注意的是C会自动的在string的末尾添加上结束符'\0'。

所以,如果我们声明了一个char类型数组 char a[6], 我们最多能往里放5个有效字符。

 

string.h 函数库中提供了一些函数可以方便我们对string的出来。在使用这些函数的时候,要特别的小心。

举个例子来说,strcat

void test()

{

  char a[20]="12345";

  char b[10]="abcdef"

  strcat(a, b[0]);

}

在这个例子中,我们想把'a' 追加到a的后面,希望出现的结果是:追加后,a变为12345a

但是在编译的过程中会报错 passing argument 2 of 'strcat' makes pointer from integer without a cast. 

看看strcat的函数原型

char * strcat ( char * destination, const char * source );

我们发现函数的第二个参数需要的是 char *, 而在上面的例子中b[0]是一个char类型的变量。既然如此,那我们改成下面的语句会发生什么的

strcat(a, &b[0]);

运行之后,结果为:12345abcdef

why???

对strcat的使用说明如下:

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.--------ref:http://www.cplusplus.com/reference/clibrary/cstring/strcat/

在追加的时候,应该是把source指定的区域追加到destination处,直到遇到'\0'。

另一个需要注意的问题是,注意destination数组的大小,如果source表示的string太大,有可能会使得destination发生栈溢出。

posted @ 2012-06-12 20:24  菜鸟的世界  阅读(1144)  评论(0编辑  收藏  举报