[英]initializing char array in main vs in a struct
im attempting to initialize an array of chars 我正在尝试初始化一个字符数组
if I do it like this in main it works fine 如果我这样做主要是可以的
char arr1[20] = "initial";
printf("%s", arr1);
but if I try to do it anywhere else such as in a struct, then try to use it in my main function like 但是,如果我尝试在其他任何地方(例如在结构中)使用它,则尝试在我的主要函数中使用它,例如
struct foo
{
char arr1[20] = "initial";
}
int main(void)
{
struct foo foobar;
printf("%s", foobar.arr1);
}
or 要么
struct foo
{
char arr1[20];
}
int main(void)
{
struct foo foobar;
foobar.arr1 = "initial";
printf("%s", foobar.arr1);
}
I start getting errors. 我开始出现错误。 Why does one work and the other doesn't?
为什么一个起作用而另一个不起作用?
Try like this.. 像这样尝试
struct foo
{
char arr1[20];
}
int main(void)
{
struct foo foobar;
strcpy(foobar.arr1,"initial");
printf("%s", foobar.arr1);
}
You are mixing up a struct definition with initialization of a variable . 您正在将结构定义与变量的初始化混合在一起。
The struct definition says which types make up a struct and what their names are, eg: struct定义说明哪些类型构成了struct及其名称是什么,例如:
struct foo
{
char arr1[20];
};
says that " struct foo
is a type we've just defined that consists of an array[20] of char
". 说“
struct foo
是我们刚刚定义的类型,它由char
的array [20]组成”。 There are no actual variables of this type yet. 尚无此类型的实际变量。
Then you can declare and initialize instances of this type, in a similar way to how you declare and initialize arr1
in your first example: 然后,可以类似于在第一个示例中声明和初始化
arr1
方式声明和初始化此类型的实例:
struct foo foobar = { "initial" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.