|
发表于 2003-10-2 22:23:28
|
显示全部楼层
可以。不过有个前提。
这里纠正一下,t2 应该是指向某个字符串的指针,该字符串的长度会随着输入变化,而不是该指针长度发生变化。
如果你是静态分配数组的。如:
char t1[100];
定义一个长度为 100 个字节的静态数组。静态的意思就是该数组的长度将不能改变。
要想把 t2 所指的字符串内容嫁接到数组 t1 原包含的字符串尾部,你要保证数组 t1 的大小足够大,能够容纳所有的字符,否则就会出现数组溢出的现象。
如果你能保证,即 t1 原有的字符串长度有个上限。 t2 所指的字符串长度也有上限,两个上限之和小于 100,那么你可以采取静态数组的方式。
- #include <stdio.h>
- #include <string.h>
- int main ()
- {
- char t1[100];
- strcpy (t1,"Hello, ");
-
- char *t2 = "world!";
- if ( strlen(t1) + strlen(t2) < sizeof(t1) )
- strcat (t1,t2);
- else {
- printf ("Array overflow!");
- return -1;}
- printf ("%s\n", t1);
- return 0;
- }
复制代码
其实为了避免由于长度的限制所带来的刚尬,我们很多时候采用动态分配数组的方式。如果有兴趣,可以查一下 malloc ,free , realloc 几个函数的用法。 |
|