簡體   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