Resizing a char[x] to char[y] at runtime

后端 未结 11 1140
我在风中等你
我在风中等你 2021-02-11 01:33

OK, I hope I explain this one correctly. I have a struct:

typedef struct _MyData
{
   char Data[256];
   int  Index;
} MyData;

Now, I run into

11条回答
  •  一个人的身影
    2021-02-11 01:52

    You would re-arrange the structure like that

    typedef struct _MyData
    {
       int  Index;
       char Data[256];
    } MyData;
    

    And allocate instances with malloc/realloc like that:

    my_data = (MyData*) malloc ( sizeof(MyData) + extra_space_needed );
    

    This is an ugly approach and I would not recommend it (I would use pointers), but is an answer to your question how to do it without a pointer.

    A limitation is that it allows for only one variable size member per struct, and has to be at the end.

提交回复
热议问题