Search code examples
cheap-memorydesignated-initializer

Using Designated Initializers with the Heap


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

Solution

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