代码之家  ›  专栏  ›  技术社区  ›  cutelittlebunny

无法将值放在由指针和malloc[复制]启动的结构中

  •  1
  • cutelittlebunny  · 技术社区  · 11 月前

    只是一个名为person的简单结构,里面需要存储姓名和年龄。我试图为我的结构体动态分配内存。

    不使用指针:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct person
    {
        char name[10];
        int age;
    } person;
    
    int main(int argc, char *argv[])
    {
        person a = {"bob", 15};    // Here, we can input values "together", all at once
        printf("name is %s, age is %i\n", a.name, a.age);
    
        return 0;
    }
    

    在这里,它可以成功打印出来: name is bob, age is 15

    使用指针:

    int main(int argc, char *argv[])
    {
        person *a = (person *) malloc(sizeof(person));
        if (a == NULL)
            return 1;
    
        *a = {"bob", 15};    // Here I tried to input the all values
        printf("name is %s, age is %i\n", a->name, a->age);
        
        free(a);
    
        return 0;
    }
    

    它不会编译并返回错误: expected expression before '{' token

    好吧,如果我试着 逐一输入值:

    int main(int argc, char *argv[])
    {
        person *a = (person *) malloc(sizeof(person));
        if (a == NULL)
            return 1;
        a->name = "bob";
        a->age = 15;
        printf("name is %s, age is %i\n", a->name, a->age);
    
        free(a);
    
        return 0;
    }
    

    它可以成功地打印出来: 名字叫鲍勃,年龄15岁

    我原本预计,由于指针指向分配给结构体的内存,因此可以像普通结构体一样一起输入值。但正如你所看到的,它不能。然而,当一个接一个地输入值时,它就起作用了。

    我做错什么了吗?或者在使用指针时,我需要逐一输入值?非常感谢。

    1 回复  |  直到 11 月前
        1
  •  0
  •   Chris    11 月前

    你可能想要一个 compound literal .

    And don't cast the return from malloc .

    int main(void)
    {
        person *a = malloc(sizeof(person));
        *a = (person){"bob", 15};    // Here I tried to input the all values
        printf("name is %s, age is %i\n", a->name, a->age);
    
        free(a);
    
        return 0;
    }
    

    你也应该养成检查的习惯,以确保 马洛克 在使用该内存之前成功。