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

后端 未结 11 1110
我在风中等你
我在风中等你 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:57

    You may be able to do this like this, without allocating a pointer for the array:

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

    Later, you allocate like this:

    int bcount = 256;
    MyData *foo;
    
    foo = (MyData *)malloc(sizeof(*foo) + bcount);
    

    realloc:

    int newbcount = 512;
    MyData *resized_foo;
    
    resized_foo = realloc((void *)foo, sizeof(*foo) + newbcount);
    

提交回复
热议问题