简体   繁体   English

初始化在C中具有确切长度的字符数组?

[英]initializing a character array with exact length in C?

char ch[2];
ch[0] = 'h';
ch[1] = '\0';

or can i just do 还是我可以做

char ch[1];
ch[0] = 'h';

in which '\\0' would already be implied? 其中已经暗示了“ \\ 0”?

The reason why i'm doing it this way is because my program has a loop in it in which i would constantly be changing this character and concatenating it to a longer string. 我这样做的原因是因为我的程序中存在一个循环,在该循环中,我将不断更改此字符并将其连接为更长的字符串。

Assigning just ch[0] will not assign zero to the ch[1] . 仅分配ch[0]不会为ch[1]分配零。 You can initialize both characters in the array with a string literal in a single line, like this: 您可以在一行中使用字符串文字初始化数组中的两个字符,如下所示:

char ch[2] = "h";

This will put 'h' into ch[0] , and a terminating zero into ch[1] . 这会将'h'放入ch[0] ,并将终止零放入ch[1]

如果愿意,您可以省略终止的空字符,但是您将无法使用需要终止的空字符的函数,例如strlen

Well, one option if you plan to be using this single-character string over and over is to just initialise the null once. 好吧,如果您打算一遍又一遍地使用此单字符字符串,一个选择是只初始化一次null。 Then you only ever have to change the first character: 然后,您只需要更改第一个字符即可:

char ch[2] = {0};
ch[0] = 'h';

In your second case, you don't need to declare an array: 在第二种情况下,您无需声明数组:

char ch = 'h';

But you can't use that as a string. 但是您不能将其用作字符串。 There is no implied null character in your single-character 'array'. 单字符“数组”中没有隐含的空字符。

Why can't you just append characters to your string instead of strings? 为什么不能仅将字符附加到字符串而不是字符串? You don't need strcat , if that's what this is about... You just keep appending single characters until you are done and then you append a null. 您不需要strcat ,如果那样的话……您只需继续添加单个字符,直到完成,然后再添加一个null即可。

char somestring[100];
char pos = 0;
while( ... ) {
    somestring[pos] = 'x';  /* or whatever */
    pos = pos + 1;
} 
somestring[pos] = 0;

ch is an char array and not a string. ch是一个char数组,而不是字符串。

The compiler can recognize it as a string only if you add the '\\0' ; 仅当您添加'\\0' ,编译器才能将其识别为字符串; however, it cannot recognize it as an array of char. 但是,它无法将其识别为char数组。

So, you must add the '\\0' , you can do like this: 因此,您必须添加'\\0' ,您可以这样做:

int ind=0;
while(...)
{
    ch[ind++]='h';
}
ch[ind]='\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM