在 C 中声明数组时,我可以编写 int array[100]={0}
并将 0 分配给所有索引。有什么办法可以用字符串做同样的事情吗?因为当我编写 char string[100]={'A'}
时,它只将“A”分配给第一个索引。当我打印字符串时,它显示“A”而不是我想要的“AAAAA.....A(99 次)”。我不想使用循环为所有索引分配“A”。那我该怎么办?
最佳答案
它不在标准中,但一些编译器(包括 gcc 和我在我的系统上测试它的 clang)允许这样做:
#include <stdio.h>
int main(){
char str[100] = {[0 ... 98] = 'A'};
str[99]='\0'; // this line is really not necessary, since default is 0 and I just wrote it for clarity
printf("%s\n", str);
return 0;
}
关于c - 用单个字符声明整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731794/