首页 > 解决方案 > malloc 嵌套变量结构数组?

问题描述

您如何正确地为如下所示的结构分配数据(为了清楚起见,尝试添加注释,但已经花费了太多时间,所以如果它们几乎没有意义,我们深表歉意)?

struct Cell
{
    int *iData;
    char *cData;
};

struct Row
{
    struct Cell *row;
};

struct Grid
{
    struct Row *grid;
    // Where maxData would be user defined
    // would be the number of elements allocated to member variables of cell
    int maxData;
    // struct Row with rowSize = 3 would be like below?
    // [*Cell][cell][cell][cell]
    int rowSize;
    // columnSize & rowSize = 3 would look something like below?
    //[*Row][*Cell][cell][cell][cell]
    //[*Row][*Cell][cell][cell][cell]
    //[*Row][*Cell][cell][cell][cell]
    int columnSize;
};



//somewhere else in program 
struct Grid *g = malloc(sizeof(struct Grid));
//make user maxData rowSize columnSize assignments here
for(int i = 0; i < g->columnSize; i++)
{
    g->grid[i] = malloc(sizeof(struct Row));
    for(int j = 0; i < g->rowSize; j++)
    {
        g->grid[i]->row[j] = malloc(sizeof(struct Cell));
        g->grid[i]->row[j]->iData = malloc((sizeof(int)) * g->maxData);
        g->grid[i]->row[j]->cData = malloc((sizeof(char)) * g->maxData);
    }
}



我的内存分配逻辑就在这里吗?

在我正在玩的数据库程序中尝试类似的东西,但是,它出现了段错误,我无法判断我对这样的嵌套结构的理解是否失败,或者我只是在该代码的其他地方有点扳手。

提前谢谢了

编辑:

我实际上试图了解如何分配的结构如下,只是举了一个例子,所以有人没有为我解决我的问题:):

struct Address {
    int id;
    int set;
    char *name;
    char *email;
};

struct Database {
    struct Address *rows;
    int maxData;
    int maxRows;
};

struct Connection {
    File *file;
    struct Database *db;
};

标签: cstructnestedmalloc

解决方案


对整个矩阵使用单个 malloc 更有用(如果可能的话)。为此,您应该使用零长度数组作为最后一个成员来组织结构:

struct grid {
    int row_count;
    int column_count; 
    int cell_capacity;       
    char data[];
};

在这种情况下,您可以分配一次内存。例如

int row_count = 2;
int column_count = 3; 
int cell_capacity = 32;

struct grid* g = calloc(1, sizeof(struct grid)+row_count*column_count*cell_capacity);
 
g->row_count = row_count;
g->column_count = column_count;
g->cell_capacity = cell_capacity;

for(int r = 0; r < row_count; ++r)
  for(int c = 0; c < column_count; ++c)
     strcpy(&g->data[r*column_count*cell_capacity + c*cell_capacity], "hello");
// (*)
free(g);

在内存中的 (*) 点,您的对象将显示如下:

在此处输入图像描述


推荐阅读