Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

c - 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
", 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 = {
               ^
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...