I have a structure
typedef struct foo { int lengthOfArray1; int lengthOfArray2; int* array1; int* array2; } foo;
I need to allocate enough memory for the whole structure and its contents of the array. Therefore, assuming that each array was 5 ...
foo* bar = (foo*)malloc(sizeof(foo) + (sizeof(int) * 5) + (sizeof(int) * 5));
Now I have to point array1 and array2 to the correct location in the allocated buffer:
bar->array1 = (int*)(&bar->lengthOfArray2 + sizeof(int)); bar->array2 = (int*)(bar->array1 + lengthOfArray2);
Is it correct?
Edit # 1
Just to eliminate any confusion: I'm trying to save memory in one block, not three.
Edit # 2
I cannot use C99 because the MSVC 2010 compiler does not support it (http://stackoverflow.com/questions/6688895/does-microsoft-visual-studio-2010-supports-c99).
source share