Using Designated Initializers with the Heap

泄露秘密 提交于 2019-12-17 20:53:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!