c - 如何使用 malloc 动态声明存在于结构中的数组

标签 c arrays struct

目前我的程序中有以下代码:

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/

相关文章:

c - 我的for循环一会儿循环不起作用吗?

在C中将多维数组转换为一维

java - 用java打印数组

c++ - 用字符串填充一个字符数组? C++

C++ 如何遍历结构列表并访问它们的属性

c - 你如何找到图中所有可达的节点

C预处理器: How to create a character literal?

c - 定义结构类型的数组

c# - C# visual studio 编译器如何处理 struct/NULL 比较?

c - 错误: ‘node’ undeclared (first use in this function)