字符串常用两种定义方式:
复制代码
1
2
3
4
5//方式1: str1指向常量全局变量区,字符串内容无法改变 char * str1 = "hell world!"; //方式2: str2是一个数组,存放于栈区,字符串内容可以改变 char str2[] = "hell world!";
字符数组:
复制代码
1
2char str3[] = {'h','e','l','l',' ','w','o','r','l','d','!'};
打印字符串,str1,str2都可以通过printf()打印,但是如果str3通过printf()打印,可能会有不可预知后果,原因就是printf根据传入的地址,一个一个字符打印,直到遇到''(''的16进制数值是0x0)。str1,str2编译时,都会在末尾加上'',但是str3不会。
比如如下测试, str3后边多了一个@字符。这是因为str3数组最后一个元素'd'后边的字节保存的是'0x40',再后边的才是'0x0'(''), 导致多打印了一个@。这是我这台机器的测试结果,实际测试时,在不同运行环境下,str3数组所在内存后边什么情况都有可能,有可能后边有许多个非'0x0'的内存字节,这样会打印很多不期待的数据,直到遇到字节值是'0x0'的才停止。所以字符数组如果末尾没有认为加上一个''元素,就不能通过printf()方式打印,必须通过for循环打印。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19#include <stdio.h> #include <string.h> int main(void) { char * str1 = "hell world"; char str2[] = "hell world"; char str3[] = {'h','e','l','l',' ','w','o','r','l','d'}; printf("%sn",str1); printf("%sn",str2); printf("%sn",str3); return 0; } ------------ ./a.out hell world hell world hell world@ <<<<<<<<<<<<<<
最后
以上就是淡淡灯泡最近收集整理的关于c 语言 字符串和字符数组的全部内容,更多相关c内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复