Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符数组结尾是否需要加\0,以及加与否的字符数组输出问题 #1

Open
Takanashi-Rikka1412 opened this issue Jun 27, 2021 · 0 comments

Comments

@Takanashi-Rikka1412
Copy link
Owner

在C/C++中,字符数组有两种用法:

一、当作字符的数组来使用

二、用于存储和处理字符串

其中,当作字符的数组时,结尾不需要加\0,然而输出时只允许循环输出每个字符。
当作字符串时,结尾必须加上\0,输出该字符串时才能识别到字符串的结尾。

下面探讨用格式输出函数输出字符数组的各种情况。(如使用printf或puts函数)

一、不定义数组长度,结尾不加\0

char c1[] = { 'a','b','c' };
printf("%d\n",sizeof(c1));
printf("%s\n", c1);

输出异常,输出函数未识别\0,输出了未使用的内存空间导致乱码,结果为:
3
abc烫烫烫烫烫烫烫烫烫烫烫烫(若干乱码)

二、定义数组长度为字符个数,结尾不加\0

char c2[3] = { 'd','e','f' };
printf("%d\n", sizeof(c2));
printf("%s\n", c2);

输出异常,输出函数未识别\0,输出了未使用的内存空间导致乱码,结果为:
3
def烫烫烫烫烫烫烫烫烫(若干乱码)

三、定义数组长度为字符个数+1,结尾不加\0

char c3[4] = { 'g','h','i' };
printf("%d\n", sizeof(c3));
printf("%s\n", c3);

输出正常,因为字符数组定义长度大于初始化的字符个数时,剩余的数组元素被赋值为\0,结果为:
4
ghi

以上三种情况,使用strlen输出的字符串结果和sizeof输出的数组长度一致

四、不定义数组长度,结尾加\0

char c11[] = { 'a','b','c','\0' };
printf("%d\n", sizeof(c11));
printf("%d\n", strlen(c11));
printf("%s\n", c11);

输出正常,其中strlen输出的字符串长度不包括\0,结果为:
4
3
abc

五、定义数组长度为字符个数,结尾加\0

char c22[3] = { 'd','e','f','\0' };

编译失败,字符数超过了定义的3。

六、定义数组长度为字符个数+1,结尾加\0

char c33[4] = { 'g','h','i','\0' };
printf("%d\n", sizeof(c33));
printf("%d\n", strlen(c33));
printf("%s\n", c33);

输出正常,结果为:
4
3
ghi

七、定义数组长度为字符个数+2,结尾加\0

char c44[5] = { 'j','k','l','\0' };
printf("%d\n", sizeof(c44));
printf("%d\n", strlen(c44));
printf("%s\n", c44);

输出正常,因为字符数组定义长度大于初始化的字符个数时,剩余的数组元素被赋值为\0,结果为:
5
3
jkl
以上三种输出的strlen字符串长度均为3,即不考虑\0,而sizeof数组长度则考虑\0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant