简体   繁体   中英

Creating a three dimensional struct array on the heap in c

I am trying to create a three dimensional struct array using malloc in c on MSVC. It compiles without error but when i debug it it gives an error after initializing some elements.

declaration:

typedef struct table_info
{
    unsigned long size;
    char code[33];
    char path[300];
}table_info;

table is a global variable and is defined as:

struct table_info ***table=NULL;

malloc and initialize table :

char garb[33] = { '\0' };
char garb_path[300] = { '\0' };

table = (table_info***)malloc(ROWS* sizeof(**table));

for (int m = 0; m < ROWS; m++)
{
    table[m] = (table_info**)malloc(COLS* sizeof(*table[m]));
    for (int j = 0; j < COLS; ++j)
    {
        table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));
        for (int k = 0; k < DEPTH; ++k)
        {
            table[m][j][k].size = 0;
            strcpy_s(table[m][j][k].code, sizeof(table[m][j][k].code), garb);
            memcpy(table[m][j][k].path, garb_path, sizeof(garb_path));
        }
    }
}

Am I initializing it correctly? or what should I correct to make it work?

The size passed to malloc is incorrect in the following line:

table[m][j] = (table_info*)malloc(DEPTH * sizeof(table[m][j]));

sizeof(table[m][j]) is just sizeof(**table) , which is sizeof(table_info *) . It should be sizeof(table_info) , or alternatively sizeof(*table_info[m][j]) or sizeof(***table_info) .

You also don't need to cast the result of malloc , which is generally frowned upon today (at least in C). See this post for more info.

So the following should work (in C):

table[m][j] = malloc(DEPTH * sizeof(*table[m][j]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM