简体   繁体   中英

Direct initialization of a struct in C

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".

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

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).

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

(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."

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

 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);


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM