Using Designated Initializers with the Heap

2019-02-25 21:06发布

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 = {
               ^

2条回答
我想做一个坏孩纸
2楼-- · 2019-02-25 21:27

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;
查看更多
Rolldiameter
3楼-- · 2019-02-25 21:45

You have to write:

*molly_ptr = (struct student){
                                .name = "molly",
                                .age = 25
                             };
查看更多
登录 后发表回答