C语言常见编程操作,却有很多需要留心细节(字符串连接操作)


 1 /*
2 * 将s,t两个字符串连接成单个字符串r
3 * */
4 #include<iostream>
5 #include<stdlib.h>
6 #include<string.h>
7 using namespace std;
8 int main() {
9 char *s = "hello ";
10 char *t = "world";
11 char *r;
12
13 r = (char *)malloc(strlen(s) + strlen(t) + 1);
14 if(!r) {
15 exit(1);
16 }
17 strcpy(r, s);
18 strcat(r, t);
19
20 cout<<r<<endl;
21
22 free(r);
23 return 0;
24 }
注意点如下:
1.malloc函数有可能无法提供请求的内存,这种情况下malloc函数会返回一个空指针来作为“内存分配失败“事件的信号。
2.strlen返回参数中字符串所包含的字符数目,而作为结束符标志的空字符(“/0”)并未计算在内,所以malloc分配内存时候需要+1。
3.给r分配的内存在使用完之后需要及时释放(显式释放内存)。

posted @ 2011-12-21 16:07  yanghuahui  阅读(197)  评论(0编辑  收藏  举报