关于C语言字符串数组
2009-04-16 10:48
375 查看
strcat函数
strcat函数用于连结两个字符串。一般形式是:
strcat(字符串1,字符串2);
strcat函数把字符串2连结在字符串1的后面。其中,参数“字符串1"必须是字符串变量,而"字符串2"则可以是字符串常量或变量。
调用strcat函数后,str1中字符后的'/0'取消,只在新串最后保留一个'/0'。
注意:strcat函数不检查字符串1的空白位置是否装得下字符串2。如果没有足够的空间,多余的字符将溢出至邻近的内存单元,破坏这些单元原来的内容。所以连结前应调用strlen函数进行检验,确保不发生溢出。记住在检验时给长度加1,为新字符串的结束符'/0'留一个位置。
例: strcat函数示例。
static char str1[30]={"Pelple's Republic of
"};/*注意空格*/
static char str2[]={"China"};
printf("%s",strcat(str1,str2));
输出:
Pelple's Republic of China
2.sizeof()
sizeof()是编译时常量,也就是它的值在编译时就已经确定了,因此无论是否对字符串做了strcat(),sizeof(s)的值不变。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//output:
//strlen=14, sizeof=15
//strlen=26, sizeof=15
//this is a test!!!!!!!!!!!!
int
main(int argc,char** argv){
// if we don't give the array lenth, sizeof(s)=strlen(s)+1=15
// static char *sp="this is a test";
static char s[]="this is a test";
// sizeof(s) is determined during compilation!!! if we change the
// string after definition, sizeof(s) will not be change.
// so it's bettern to use strlen
printf("strlen=%d, sizeof=%d/n",strlen(s),sizeof(s)); //sizeof(s)=15
strcat(s,"!!!!!!!!!!!!"); // BE CAREFUL to do this :s[] overflow!!!
// we should allocate a big enough s[100].
// but on some machine this will produce
// the expected result.
printf("strlen=%d, sizeof=%d/n",strlen(s),sizeof(s)); //sizeof(s)=15
printf(s);
}
相关文章推荐
- C语言--关于二维数组,字符串数组,多维数组
- c语言中关于字符串的那些事儿(字符数组和字符指针)
- 关于字符串数组,字符串指针(C语言)
- C语言:字符串、结构体中关于数组的几个问题
- 关于c语言中的字符数组和字符串指针
- 关于C语言字符数组、字符串和指针的相关问题
- C语言中关于数组与指针和字符串与指针的小结
- 关于C语言,字符数组中越界的两个问题
- 第08天C语言(08):字符串数组
- C语言的数组、字符串等一些知识总结
- C语言中字符串和字符数组
- 黑马程序员——c语言的进制表达方式,位运算,数组,字符串数组
- 重学C语言(一) 字符串数组输出
- 小小的C语言问题指针数组赋值----关于指针和数组。
- 关于c语言中的字符数组的输入问题
- 黑马程序员 C语言 - 06 数组、二维数组、字符串
- C语言中字符串与字符数组的使用
- C/C++关于字符串string、char*字符串数组与其他类型转换
- 关于指针 用字符数组,字符指针变量输入字符串 动态为字符型指针变量分配内存
- 关于字符串数组-------来自他人的哦