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 a problem. Most of the time MyData.Data is OK with 256, but in some cases I need to expand the amount of chars it can hold to different sizes.
I can’t use a pointer.
Is there any way to resize Data at run time? How?
Code is appreciated.
EDIT 1:
While I am very thankful for all the comments, the "maybe try this…" or "do that", or "what you are dong is wrong…" comments are not helping. Code is the help here. Please, if you know the answer post the code.
Please note that:
- I cannot use pointers. Please don’t try to figure out why, I just can’t.
- The struct is being injected into another program’s memory that’s why no pointers can be used.
Sorry for being a bit rough here but I asked the question here because I already tried all the different approaches that thought might work.
Again, I am looking for code. At this point I am not interested in "might work…" or " have you considered this…"
Thank you and my apologies again.
EDIT 2
Why was this set as answered?
You can use a flexible array member
So that you can then allocate the right amount of space
Later, you can free, and allocate another chunk of memory and make a pointer to
MyDatapoint 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 therechar *Dataand 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.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.