Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c - Allocating memory for a 2-dimensional array that is in a structure

For my project I had to save my data in a dynamic data structure (dynamic array, dynamic list etc..) which size and capacity would be set during execution time with malloc() as I suppose. I completely forgot about it and I was working with that data without allocating any 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"}}};
}

This is what I am working with. I am confused how should I do this. Do I do

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

Then in main I create that Bet betTypes; do betTypes.x = 3; and betTypes.y = 2 and call malloc() using those x and y? But then how do I create that exact same list of strings, because I didn't find any another ways aside Bet betTypes = { .bets={{"Red", "Black"}, {"Even", "Odd"}, {"1 to 18", "19 to 36"}}};, if I declared Bet betTypes; before that, then the Bet betTypes = { .bets={{"Red", "Black"}, {"Even", "Odd"}, {"1 to 18", "19 to 36"}}}; part would not work. Or I suppose I am just too unexperienced with memory allocation and I don't know how this should look like (neither I don't know how to allocate memory for this array)

question from:https://stackoverflow.com/questions/65908917/allocating-memory-for-a-2-dimensional-array-that-is-in-a-structure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...