繁体   English   中英

为结构中的二维数组分配 memory

[英]Allocating memory for a 2-dimensional array that is in a structure

对于我的项目,我必须将我的数据保存在一个动态数据结构(动态数组、动态列表等)中,我想在执行期间使用malloc()设置大小和容量。 我完全忘记了它,我正在处理这些数据而没有分配任何 memory。

#include <stdio.h>
#include <stdlib.h>

typedef struct Bet {
    char* bets[3][2];
} Bet;

int main() {
     Bet betTypes = { .bets={{"Red", "Black"}, {"Even", "Odd"}, {"1 to 18", "19 to 36"}}};
}

这就是我正在使用的。 我很困惑我该怎么做。 我做吗

typedef struct Bet {
    int x;
    int y;
    char* bets[x][y];
} Bet;

然后我主要创建Bet betTypes; betTypes.x = 3; betTypes.y = 2并使用这些 x 和 y 调用malloc() 但是我该如何创建完全相同的字符串列表,因为除了Bet betTypes = {.bets={{"Red", "Black"}, {"Even", "Odd"}, {"1 to 18", "19 to 36"}}}; , 如果我声明Bet betTypes; 在此之前,然后Bet betTypes = {.bets={{"Red", "Black"}, {"Even", "Odd"}, {"1 to 18", "19 to 36"}}}; 部分不起作用。 或者我想我对 memory 分配太缺乏经验,我不知道这应该是什么样子(我也不知道如何为这个数组分配 memory)

typedef struct
{
    size_t x,y;
    int data[];
}mydata_t;


mydata_t *allocate(size_t x, size_t y)
{
    mydata_t *mydata = malloc(sizeof(*mydata) + x * y * sizeof(mydata -> data[0]));

    if(mydata) 
    {
        mydata -> x = x;
        mydata -> y = y;
    }
    return mydata;
}

int getval(mydata_t *sptr, size_t x, size_t y)
{
    return sptr -> data[x + sptr -> x * y];
}

您可以在符合 C99 的编译器(或实现它们的 C11 和更高版本的编译器)上使用 VLA:

#include <stdint.h>
#include <stdlib.h>

struct Bet
{
    uint32_t x;
    uint32_t y;
    void *bets;
};

struct Bet *allocateBet( uint32_t x, uint32_t y )
{
    struct Bet *b = malloc( sizeof( *b ) );
    if ( NULL == b )
    {
        return( NULL );
    }

    b->x = x;
    b->y = y;

    char *( *array )[x][y] = calloc( 1, sizeof( *array ) );

    b->bets = array;

    return( b );
}

并轻松获取和设置值:

char *getBet( struct Bet *b, uint32_t x, uint32_t y )
{
    char *( *array )[b->x][b->y] = b->bets;
    return( ( *array )[x][y] );
}

void setBet( struct Bet *b, uint32_t x, uint32_t y, char *bet )
{
    char *( *array )[b->x][b->y] = b->bets;

    // might want to use strdup() here:
    // if ( ( *array )[x][y] )
    // {
    //     free( ( *array )[x][y] );
    // }
    // ( *array )[x][y] = strdup( bet );

    ( *array )[x][y] = bet;
}

释放结构:

void freeBet( struct Bet *b )
{
    // if strdup() is used in setBet:
    // char *( *array )[b->x][b->y] = b->bets;
    // for ( uint32_t ii = 0; ii < b->x; ii++ )
    // {
    //     for ( uint32_t jj = 0; jj < b->y; jj++ )
    //     {
    //         free( ( *array )[ii][jj] );
    //     }
    // }

    free( bet->bets );
    free( bet );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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