将指定的初始化程序与堆一起使用

将指定的初始化程序与堆一起使用

本文介绍了将指定的初始化程序与堆一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人可以使用designated initializers,如下所示(对于"billy"而言),没有问题,但是当对动态内存使用相同的初始化方法时,在编译时它将中断.

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?

除了我们要写入的 where (即地址)之外,这两个初始化有何不同?为什么我们不能在动态内存中使用指定的初始值设定项?

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

推荐答案

使用复合文字:

*molly_ptr = ( struct student ){ .name = "molly", .age = 25 };

这几乎等同于:

struct student temp = { .name = "molly", .age = 25 };
*molly_ptr = temp;

这篇关于将指定的初始化程序与堆一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:30