【发布时间】:2021-09-25 14:25:44
【问题描述】:
我尝试使用 = 运算符从相同类型结构的数组中分配结构变量值,如下所示:
struct s {
int dummy;
char somechar[8];
} array_of_s[10];
void f(void)
{
struct s a = array_of_s[0]; // this line gives me error message
}
int main(void)
{
f();
return 0;
}
我收到一条错误消息,上面写着:
a value of type "struct s" cannot be used to initialize an entity of type "struct s"C/C++(144)
但如果我像下面这样将数组作为参数传递,它就像一个魅力:
struct s {
int dummy;
char somechar[8];
} array_of_s[10];
void f(struct s array_as_parameter[])
{
struct s a = array_as_parameter[0];
}
int main(void)
{
f(array_of_s);
return 0;
}
为什么第一个代码是非法的?我不应该能够访问外部数组变量并分配它吗?
【问题讨论】:
-
尝试使用赋值而不是初始化。