在c中为结构中的数组赋值
我创建: 结构学生 在我的.c文件中 如果我尝试使用在c中为结构中的数组赋值,c,arrays,struct,C,Arrays,Struct,我创建: 结构学生 在我的.c文件中 如果我尝试使用 struct student { int marks[3]; int numberofsubjects[3]; }; 我确实看到了错误:在“{”标记之前应该有表达式 有什么我遗漏的吗?您遗漏的主要事情是无法分配完整的数组;这只允许在定义变量的过程中进行(这称为初始化),但一旦定义了变量,就不再允许这样做 请参阅以下初始化(这是允许的): 您只能在定义变量时使用初始值设定项。您不能定义变量,然后尝试稍后使用初始值设定项对其进行初始化。您必须为
struct student {
int marks[3];
int numberofsubjects[3];
};
我确实看到了错误:在“{”标记之前应该有表达式
有什么我遗漏的吗?您遗漏的主要事情是无法分配完整的数组;这只允许在定义变量的过程中进行(这称为初始化),但一旦定义了变量,就不再允许这样做 请参阅以下初始化(这是允许的):
您只能在定义变量时使用初始值设定项。您不能定义变量,然后尝试稍后使用初始值设定项对其进行初始化。您必须为结构的数组字段的元素赋值,或者在定义时使用初始值设定项
struct student {
int marks[3];
int numberofsubjects[3];
};
int main() {
struct student s = { {1,2,3},{3,4,5}}; // in the course of variable definition; OK, this is "initialization"
// s.marks = { 2,3,4 }; // illegal assignment of array
return 0;
}
或者最好使用指定的初始值设定项:
该结构定义甚至没有在Clang、GCC或MSVC上为我编译,因为他们都希望一个结构最多只能有一个灵活的数组作为结构的最后一个成员。对不起,我错过了数组大小。我可以有结构学生s的可能重复;在.h文件和.c文件中定义为s={.marks={99,99},.numberofsubjects={1,2,3};@shivaniarin--no.您可以在
.h.
文件中声明类型struct student{}
,但是您只能在使用struct student s={.marks={99,99,99},/*.*/}定义s
时使用初始值设定项。该定义可以是(应该是)在.c
文件中。我在.h文件中定义了struct student,在.c文件中定义了struct student;s={.marks={99,99},…}->这行吗?这是一个错误me@ShivaniSarin--同样,这不起作用。您只能在定义时使用初始值设定项语法。您不能将struct student s;
与s=/*…*/;
分开。这唯一有效的方法是使用struct student s={/*…*/}
在同一行。struct student s
是变量s
的定义。如果这样做:struct student s;
那么s=/*…*/;
在定义之后尝试初始化(实际上是尝试非法赋值。使用struct student s={'*…*/};
您在同一行上定义和初始化。我明白您的意思。:)但是如果我在一个函数中设置它,并想在另一个函数中使用它,该怎么办?在这种情况下,我如何将它设置为全局变量?
struct student {
int marks[3];
int numberofsubjects[3];
};
int main() {
struct student s = { {1,2,3},{3,4,5}}; // in the course of variable definition; OK, this is "initialization"
// s.marks = { 2,3,4 }; // illegal assignment of array
return 0;
}
struct student student = { { 99, 99, 99 },
{ 1, 2, 3 } };
struct student student = { .marks = { 99, 99, 99 },
.numberofsubjects = { 1, 2, 3 }};