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

后端 未结 11 1139
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    2021-02-11 01:52

    You can use a flexible array member

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

    So that you can then allocate the right amount of space

    MyData *d = malloc(sizeof *d + sizeof(char[100]));
    d->Data[0..99] = ...;
    

    Later, you can free, and allocate another chunk of memory and make a pointer to MyData point to it, at which time you will have more / less elements in the flexible array member (realloc). Note that you will have to save the length somewhere, too.

    In Pre-C99 times, there isn't a flexible array member: char Data[] is simply regarded as an array with incomplete type, and the compiler would moan about that. Here i recommend you two possible ways out there

    • Using a pointer: char *Data and make it point to the allocated memory. This won't be as convenient as using the embedded array, because you will possibly need to have two allocations: One for the struct, and one for the memory pointed to by the pointer. You can also have the struct allocated on the stack instead, if the situation in your program allows this.
    • Using a char Data[1] instead, but treat it as if it were bigger, so that it overlays the whole allocated object. This is formally undefined behavior, but is a common technique, so it's probably safe to use with your compiler.

提交回复
热议问题