C语言 C 字符数组初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18688971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C char array initialization
提问by lkkeepmoving
I'm not sure what will be in the char array after initialization in the following ways.
我不确定通过以下方式初始化后 char 数组中的内容。
1.char buf[10] = "";
2. char buf[10] = " ";
3. char buf[10] = "a";
1. char buf[10] = "";
2. char buf[10] = " ";
3.char buf[10] = "a";
For case 2, I think buf[0]should be ' ', buf[1]should be '\0', and from buf[2]to buf[9]will be random content. For case 3, I think buf[0]should be 'a', buf[1]should be '\0', and from buf[2]to buf[9]will be random content.
对于情况 2,我认为buf[0]should be ' '、buf[1]should be'\0'和 from buf[2]tobuf[9]将是随机内容。对于情况3,我认为buf[0]应该是'a',buf[1]应该是“\ 0”,以及buf[2]到buf[9]会随机内容。
Is that correct?
那是对的吗?
And for the case 1, what will be in the buf? buf[0] == '\0'and from buf[1]to buf[9]will be random content?
对于案例 1,将是什么buf?buf[0] == '\0'和 from buf[1]tobuf[9]将是随机内容?
回答by ouah
This is not how you initialize an array, but for:
这不是初始化数组的方式,而是用于:
The first declaration:
char buf[10] = "";is equivalent to
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};The second declaration:
char buf[10] = " ";is equivalent to
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};The third declaration:
char buf[10] = "a";is equivalent to
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
第一个声明:
char buf[10] = "";相当于
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};第二个声明:
char buf[10] = " ";相当于
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};第三个声明:
char buf[10] = "a";相当于
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.
如您所见,没有随机内容:如果初始化器较少,则数组的其余部分用0. 即使在函数内部声明数组也是如此。
回答by verbose
Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.
编辑:OP(或编辑器)在我提供此答案后的某个时候默默地将原始问题中的一些单引号更改为双引号。
Your code will result in compiler errors. Your first code fragment:
您的代码将导致编译器错误。你的第一个代码片段:
char buf[10] ; buf = ''
is doubly illegal. First, in C, there is no such thing as an empty char. You can use double quotes to designate an empty string, as with:
双重违法。首先,在 C 中,没有空的char. 您可以使用双引号来指定空字符串,例如:
char* buf = "";
That will give you a pointer to a NULstring, i.e., a single-character string with only the NULcharacter in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NULcharacter, you have to specify it:
这会给你一个指向NUL字符串的指针,即一个只有NUL字符的单字符字符串。但是你不能使用没有任何内容的单引号——这是未定义的。如果需要指定NUL字符,则必须指定它:
char buf = 'char buf = 0;
';
The backslash is necessary to disambiguate from character '0'.
反斜杠是消除字符歧义所必需的'0'。
char buf[10];
accomplishes the same thing, but the former is a tad less ambiguous to read, I think.
完成同样的事情,但我认为前者读起来不那么模棱两可。
Secondly, you cannot initialize arrays after they have been defined.
其次,您不能在定义数组后对其进行初始化。
buf = // anything on RHS
declares and defines the array. The array identifier bufis now an address in memory, and you cannot change where bufpoints through assignment. So
声明并定义数组。数组标识符buf现在是内存中的一个地址,您无法buf通过赋值更改指向的位置。所以
char buf [10] = ' ';
is illegal. Your second and third code fragments are illegal for this reason.
是非法的。由于这个原因,您的第二个和第三个代码片段是非法的。
To initialize an array, you have to do it at the time of definition:
要初始化数组,您必须在定义时进行:
char buf [10];
will give you a 10-character array with the first char being the space '\040'and the rest being NUL, i.e., '\0'. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0. There will not be any "random content".
将为您提供一个 10 个字符的数组,其中第一个字符是空格'\040',其余字符是NUL,即'\0'. 当使用初始化程序声明和定义数组时,超过具有指定初始值的数组元素(如果有)将自动填充0. 不会有任何“随机内容”。
If you declare and define the array but don't initialize it, as in the following:
如果您声明并定义了数组但未对其进行初始化,如下所示:
char buf[10] = "";
char buf[10] = {0};
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
you will have random content in all the elements.
您将在所有元素中包含随机内容。
回答by Steven Penny
These are equivalent
char buf[10] = " "; char buf[10] = {' '}; char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};These are equivalent
char buf[10] = "a"; char buf[10] = {'a'}; char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};These are equivalent
char buf[10] = ""; char buf[10] = {0}; char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
这些是等价的
char buf[10] = " "; char buf[10] = {' '}; char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};这些是等价的
char buf[10] = "a"; char buf[10] = {'a'}; char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};这些是等价的
#include <stdio.h> struct ccont { char array[32]; }; struct icont { int array[32]; }; int main() { int cnt; char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '
', '##代码##', ... int iarray[32] = { 67, 42, 25 }; struct ccont cc = { 0 }; struct icont ic = { 0 }; /* these don't work carray = { [0]=1 }; // expected expression before '{' token carray = { [0 ... 31]=1 }; // (likewise) carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *' iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g) */ // but these perfectly work... cc = (struct ccont){ .array='a' }; // 'a', '##代码##', '##代码##', '##代码##', ... // the following is a gcc extension, cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '##代码##', '##代码##', ... ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ... // index ranges can overlap, the latter override the former // (no compiler warning with -Wall -Wextra) ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ... for (cnt=0; cnt<5; cnt++) printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]); return 0; }main() { void something(char[]); char s[100] = ""; something(s); printf("%s", s); } void something(char s[]) { // ... do something, pass the output to s // no need to add s[i] = '##代码##'; because all unused slot is already set to '##代码##' }
回答by Antti Haapala
The relevant part of C11 standard draft n1570 6.7.9 initialization says:
C11标准草案n1570 6.7.9初始化的相关部分说:
14An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
14字符类型的数组可以由字符串文字或 UTF-8 字符串文字初始化,可选地括在大括号中。字符串文字的连续字节(如果有空间或数组大小未知,则包括终止空字符)初始化数组元素。
and
和
21If there arefewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
21如果花括号括起来的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小数组的字符串文字中的字符少于数组中的元素,聚合的剩余部分应与具有静态存储持续时间的对象一样隐式初始化。
Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c;would be initialized within a function.
因此,如果有足够的空间,则附加 '\0' ,其余字符将使用static char c;将在函数内初始化的值进行初始化。
Finally,
最后,
10If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has staticor thread storage duration is not initialized explicitly, then:
[--]
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
[--]
10如果没有明确初始化具有自动存储期的对象,则其值是不确定的。如果没有显式初始化具有静态或线程存储持续时间的对象,则:
[--]
- 如果它有算术类型,则初始化为(正或无符号)零;
[--]
Thus, charbeing an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.
因此,char作为算术类型,数组的其余部分也保证用零初始化。
回答by user3381726
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a structor union.
有趣的是,可以在程序中的任何时间以任何方式初始化数组,只要它们是 astruct或 的成员union。
Example program:
示例程序:
##代码##回答by Erric Rapsing
I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.
我不确定,但我通常将数组初始化为 "",在这种情况下,我不需要担心字符串的空结尾。
##代码##
