
1.使用场合
* 一维字符数组中存放一个字符串,比如一个名字char name[20] = "mj"
* 如果要存储多个字符串,比如一个班所有学生的名字,则需要二维字符数组,char names[15][20]可以存放15个学生的姓名(假设姓名不超过20字符)
* 如果要存储两个班的学生姓名,那么可以用三维字符数组char names[2][15][20]
2.初始化
char names[2][10] = { {'J','a','y','\0'}, {'J','i','m','\0'} };
char names2[2][10] = { {"Jay"}, {"Jim"} };
char names3[2][10] = { "Jay", "Jim" };
3.代码
1 #include <stdio.h>
2
3 int main()
4 {
5 //char name[] = {'i', 't', 'c', 'H', 's', 't', '\0'};
6 char name[] = "itcast";
7
8 name[3] = 'H';
9
10 /*
11 int size = sizeof(name);
12
13 PRintf("%d\n", size);
14 */
15
16 printf("我在%s上课\n", name);
17
18 return 0;
19 }
20
21 // 字符串的一个初始化
22 void test2()
23 {
24 // \0的ASCII码值是0
25 // 都是字符串
26 char name[8] = "it";
27 char name2[8] = {'i', 't', '\0'};
28 char name3[8] = {'i', 't', 0};
29 char name4[8] = {'i', 't'};
30
31 // 不算是一个字符串(只能说是一个字符数组)
32 char name5[] = {'i', 't'};
33 }
34
35 /*
36 void test()
37 {
38 // 'a' 'b' 'A'
39 // "jack" == 'j' + 'a' + 'c' + 'k' + '\0'
40
41 char name[10] = "jack888\n";
42
43 // 把数组传入,仅仅是个警告
44 printf(name);
45
46 printf(name);
47
48 printf(name);
49
50 printf("57843578435");
51 }*/
注意
1 #include <stdio.h>
2
3 /*
4 \0的作用
5 1.字符串结束的标记
6 2.printf("%s", name2);
7 会从name2这个地址开始输出字符,直到遇到\0为止
8 */
9
10 int main()
11 {
12 char name[] = "itc\0ast";
13
14 char name2[] = {'o', 'k'};
15
16 //printf("%s\n", name2);
17
18 printf("%s\n", &name2[1]);
19
20 return 0;
21 }