目前我的程序中有以下代码:
struct mystruct
{
int x;
struct y *list[10];
}
mystruct *h1=(mystruct *)malloc(sizeof(mystruct));
我想在声明结构时动态声明数组list
(使用malloc()
)。谁能告诉我该怎么做?
最佳答案
您需要明确地执行此操作。我通常使用这样的包装函数来执行此操作。
编辑:现在底部有一个完整的工作示例。
struct mystruct *mystruct_init()
{
struct mystruct *mystruct = calloc(1, sizeof(*mystruct));
// loop through and allocate memory for each element in list
for (int i = 0; i < 10; i++) {
mystruct->list[i] = calloc(1, sizeof(*(mystruct->list[i])));
}
return mystruct;
}
这样,您只需在代码中调用它:
struct mystruct *h1 = mystruct_init();
您还需要编写相应的 mystruct_free()
函数。
这是一个工作示例(对我而言):
#include <stdlib.h>
#include <stdio.h>
struct y {
int a;
};
struct mystruct {
int x;
struct y **list;
int list_length;
};
struct mystruct *mystruct_init()
{
struct mystruct *mystruct = calloc(1, sizeof(*mystruct));
// loop through and allocate memory for each element in list
mystruct->list_length = 10;
mystruct->list = calloc(1, sizeof(struct y *) * mystruct->list_length);
for (int i = 0; i < mystruct->list_length; i++) {
mystruct->list[i] = calloc(1, sizeof(struct y));
}
return mystruct;
}
void mystruct_free(struct mystruct *mystruct)
{
for (int i = 0; i < mystruct->list_length; i++) {
free(mystruct->list[i]);
}
free(mystruct->list);
free(mystruct);
}
int main(int argc, char *argv[])
{
struct mystruct *h1 = mystruct_init();
h1->x = 6;
printf("%d\n", h1->x);
mystruct_free(h1);
return 0;
}
关于c - 如何使用 malloc 动态声明存在于结构中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9085051/