I have a structure
typedef struct foo {
int lengthOfArray1;
int lengthOfArray2;
int* array1;
int* array2;
} foo;
I need to allocate enough memory for the entire structure and its array's contents. So assuming each array had a length of 5...
foo* bar = (foo*)malloc(sizeof(foo) + (sizeof(int) * 5) + (sizeof(int) * 5));
I now have to point array1 and array2 to the correct location in that allocated buffer:
bar->array1 = (int*)(&bar->lengthOfArray2 + sizeof(int));
bar->array2 = (int*)(bar->array1 + lengthOfArray2);
Is this correct?
Edit #1
Just to clear up any confusion: I am trying to keep the memory in one block, and not three.
Edit #2
I cannot use C99 as the MSVC 2010 compiler does not support it (http://stackoverflow.com/questions/6688895/does-microsoft-visual-studio-2010-supports-c99).
With a little extra memory (only for C99):
You have to allocate the sizeof the structure. You then have to allocate the array of ints with their respective sizes.
Following the OP's approach this should do the job: