I understand how to create a struct that can be used to access an array, for example:
#include <stdio.h>
typedef struct {
int i;
int j;
int k;
} MyStruct;
int main()
{
MyStruct *ms;
int array[9];
int i;
for(i=0;i<9;++i) array[i] = i;
ms = (MyStruct *)array;
for(i=0;i<3;++i) printf("%d %d %d %d\n",i,ms[i].i,ms[i].j,ms[i].k);
return 0;
}
which allows me to access array[0] as ms[1].i and array[1] as ms[1].j etc.. However, how could I do the same thing if I wanted to use an array in the struct that is known at runtime but not at compile time? Something like:
#include <stdio.h>
typedef struct {
int *myArgs;
} MyStruct;
int main()
{
MyStruct *ms;
int array[9];
int i;
for(i=0;i<9;++i) array[i] = i;
ms = (MyStruct *)array;
for(i=0;i<3;++i) printf("%d %d %d %d\n",i,ms[i].myArgs[0],ms[i].myArgs[1],ms[i].myArgs[2]);
return 0;
}
which in that example, I would know at runtime that myArgs is length 3. But it's also possible myArgs is length 9, in which case ms should be length 1.
Edit:
I'm storing a solution set for a PDE solver that has a number of fixed-at-compile-time knowns and then an unknown number of extras. For example, my array will have X, Y, Z but then it might have 3 or 5 or 10 more things after that. So, I wanted to provide a structure that gives access to the fields for easy readability later, for example solution.x, solution.y, solution.z, solution.chemicalSpecies[0], solution.chemicalSpecies[1], etc.. The number of species is entirely unknown at compile time.
I'm using an outside library that stores the number of unknowns as an array, and I can get the array back in the form [k][j][i][numUnknowns] and it would be nice to give access like solution[k][j][i].something.
-fstrict-aliasing, you'll probably get bogus results.