在C中直接初始化结构

时间:2022-07-25 18:53:57

I have:

struct date
{
int day;
int month;
int year;
};

struct person {
char name[25];
struct date birthday;
};


struct date d = { 1, 1, 1990 }; 

Initialization with

struct person p1 = { "John Doe", { 1, 1, 1990 }};

works.

But if I try

但是,如果我尝试

struct person p2 = { "Jane Doe", d};

I get an error like:

我得到一个错误:

"Date can't be converted to int".

“日期无法转换为int”。

Whats wrong? d is a struct date and the second parameter should be a struct date as well. So it should work. Thanks and regards

怎么了? d是结构日期,第二个参数也应该是结构日期。所以它应该工作。感谢致敬

2 个解决方案

#1


struct person p2 = { "Jane Doe", d};

It can be declared this way only if the declaration is at block scope. At file scope, you need constant initializers (d is an object and the value of an object is not a constant expression in C).

只有当声明在块范围内时,才能以这种方式声明它。在文件范围,您需要常量初始值设定项(d是对象,对象的值不是C中的常量表达式)。

The reason for this is that an object declared at file-scope without storage-class specifier has static storage duration and C says:

原因是在没有存储类说明符的文件范围内声明的对象具有静态存储持续时间,C表示:

(C11, 6.7.9p4) "All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals."

(C11,6.7.9p4)“具有静态或线程存储持续时间的对象的初始化程序中的所有表达式应为常量表达式或字符串文字。”

At block-scope without storage class specifier, the object has automatic storage duration.

在没有存储类说明符的块范围内,该对象具有自动存储持续时间。

#2


 I would suggest that to try :) 

struct person

{

  float salary;

  int age;

  char name[20];

};

int main(){

struct person person1={21,25000.00,"Rakibuz"};

 printf("person name: %s  \n",person1.name);

 printf("person age: %d\n",person1.age);

 printf("person salary: %f\n",person1.salary);


}

#1


struct person p2 = { "Jane Doe", d};

It can be declared this way only if the declaration is at block scope. At file scope, you need constant initializers (d is an object and the value of an object is not a constant expression in C).

只有当声明在块范围内时,才能以这种方式声明它。在文件范围,您需要常量初始值设定项(d是对象,对象的值不是C中的常量表达式)。

The reason for this is that an object declared at file-scope without storage-class specifier has static storage duration and C says:

原因是在没有存储类说明符的文件范围内声明的对象具有静态存储持续时间,C表示:

(C11, 6.7.9p4) "All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals."

(C11,6.7.9p4)“具有静态或线程存储持续时间的对象的初始化程序中的所有表达式应为常量表达式或字符串文字。”

At block-scope without storage class specifier, the object has automatic storage duration.

在没有存储类说明符的块范围内,该对象具有自动存储持续时间。

#2


 I would suggest that to try :) 

struct person

{

  float salary;

  int age;

  char name[20];

};

int main(){

struct person person1={21,25000.00,"Rakibuz"};

 printf("person name: %s  \n",person1.name);

 printf("person age: %d\n",person1.age);

 printf("person salary: %f\n",person1.salary);


}