C中struct中数组和字符串的动态内存分配

Dynamic memory allocation for arrays and strings in struct in C

我想创建一个结构,但我也想用动态内存分配来编写它的数组或字符串元素。

struct st {
    char *name[40];
    int age;
};

对于 "name" string,我应该在 struct 之前使用 malloc,还是我也可以在 struct 中使用它。

1)

char *name = malloc(sizeof(char)*40);

struct st {
    char *name;
    int age;
};

2)

struct st {
    char *name = malloc(sizeof(char)*40);
    int age;
};

两者都是真的还是有误?如果两者都是真的,那哪个对代码的其他部分更有用?

一个选项是在结构中有一个指针,但是在您使用它的函数中在结构之外分配内存。

例如

struct st {
    char* n;
    int a;
};

void foo() {
    char* name = malloc(sizeof(char) * 40);
    int age = 0;

    struct st s = (struct st) {
        .n = name,
        .a = age,
    };

    /* TO DO */

    free(name);
}

您需要创建结构的实例,它的实际变量。然后需要在函数中初始化结构体实例的成员

例如,在某些函数中你可以做

struct st instance;
instance.name = malloc(...);  // Or use strdup if you have a string ready
instance.age = ...;

声明类型不会创建左值(如变量)。它定义左值的格式。在 1) 中,您已经正确地声明了一个结构类型,但您似乎已经假定结构声明中 "name" 变量的相似性会将指针 "name" 关联到结构成员 "name"。它不是那样工作的。

2) syntactically/symantically 错误。您根本无法将 malloc() 分配给非左值(因为您正在声明类型结构)

因此,按照您在 1) 中创建的结构类型创建一个变量,并在结构变量成员中分配内存。

typedef struct st {
    char *name;
    int age;
} st_type;

st_type st_var;
st_var.name = (char *) malloc(sizeof(char) * 40); // This is how you will allocate the memory for the struct variable.

记住,在进行动态分配之前,您需要有一个左值,就像您为独立 "name" 变量所做的那样。