问题描述
C中的字符串常量存储为一个字符数组,在逐个元素地创建这种数组时,必须提供空字符.
A string constant in C is stored as a character array, while creating such an array element by element, is it necessary to supply the null character.
我需要存储一个字符串常量,例如S[number]= "hello\n"
.字符串常量作为字符数组存储在C中,此外,这样的字符串以空字符'\0'
结尾.将短语存储在数组中时,我是否需要考虑空字符并分配额外的空间,还是只需要提及需要存储的字符数?
I need to store a string constant, say, S[number]= "hello\n"
. A string constant is stored as a character array in C, further, such a string is terminated by a null character '\0'
. While storing the phrase in an array, do I need to account for the null character and allocate an additional space or do I just need to mention the number of characters that I need to store?
推荐答案
如果要使用strlen之类的C字符串函数,则答案为 YES .您的字符串应以空值结尾.如果您引入自定义函数来处理字符串-您可以根据需要存储它.
If you are going to use C-string functions, like strlen, - then answer is YES. Your string should be null-terminated. If you introduce your custom functions to deal with string - you can store it however you like.
重要的是要提到,如果您使用字符串常量创建一个数组,它将自动为空字符保留空间.例如.输出以下代码:
It's important to mention, that if you create an array using string constant, it reserves space for null-character automatically. E.g. output for the following code:
char s[] = "hello";
printf("%d", sizeof(s) / sizeof(char));
是
6
对于'h,'e','l','l','o'为5,对于'\ 0'为1.
which is 5 for 'h, 'e', 'l', 'l', 'o' and 1 for '\0'.
这篇关于声明字符数组时是否必须提供空字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!