我想用一个具有初始默认值的结构变量在C中创建一个结构
struct process{
char process_name[2];
int burst_time;
int completion_time;
int turn_around_time;
int waiting_time;
int priority;
int arrival_time= 0;
};
在上述结构中,我想使arrival_time = 0,但是我给我一个错误
Priority.c:11:19: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
答案 0 :(得分:2)
在C语言中,这是不可能的。您不能在结构本身内部初始化结构成员。首先,您需要创建结构类型的实例或变量;只有在那之后,您才能初始化结构成员。例如:
struct process{
char process_name[2];
int burst_time;
int completion_time;
int turn_around_time;
int waiting_time;
int priority;
int arrival_time; /* here you can't initialize */
} process_instance = { .arrival_time = 0 }; /* first process_instance created then initialize the members */
您可以像下面的arrival_time
一样访问。
int main(void) {
printf("%d\'n",process_instance.arrival_time);
return 0;
}
尽管在 C ++(不是C语言)中,结构几乎等同于类,并且可以在构造函数中初始化成员。例如:
struct process{
int arrival_time; /* member of structure */
process() : arrival_time(0) { } /*constructor */
};
int main(void) {
process obj;
std::cout<<obj.arrival_time;
return 0;
}