问题
One can use designated initializers
as shown below (for "billy") without issue, but when the same initialization approach is used on dynamic memory things will break at compile-time.
What are the restrictions for using designated initializers?
Aside from where (i.e. the address) to which we are writing, what makes these two initializations different? Why can we not use designated initializers with dynamic memory?
struct student{
char *name;
int age;
};
void print_student(struct student* st){
printf("Student: %s is %d years old\n", st->name, st->age);
}
int main(void) {
srand(time(NULL));
struct student *molly_ptr = malloc(sizeof(struct student));
struct student billy = {
.name = "billy",
.age = rand()%30
};
*molly_ptr = {
.name = "molly",
.age = 25
};
//molly_ptr->name = "molly";
//molly_ptr->age = 25;
print_student(&billy);
print_student(molly_ptr);
return 0;
}
error: expected expression before '{' token
*molly_ptr = {
^
回答1:
Use a compound literal:
*molly_ptr = ( struct student ){ .name = "molly", .age = 25 };
This is almost identical to:
struct student temp = { .name = "molly", .age = 25 };
*molly_ptr = temp;
回答2:
You have to write:
*molly_ptr = (struct student){
.name = "molly",
.age = 25
};
来源:https://stackoverflow.com/questions/35436554/using-designated-initializers-with-the-heap