C : Static to dynamic allocation on multiple dimension array
I'm currently stuck with a legacy code using multiple dimensions arrays :
#define B 25
int Table[A][B][C][D][E][F];
I need to change the B constant by a dynamic value. The thing is, I need to keep the table the same way it used to be so that I won't have anything else but the allocati开发者_StackOverflow中文版on du rewrite.
I'd like to have your ideas / comments on how to do such a thing.
Currently I'm trying to typedef the end of the table ([C][D][E]) to malloc it at allocation time, but I'm stuck with errors about the Table not being as legacy code wants it ...
//int32_t Table[A][B][C][D][E][F];
int32_t* Table[A];
typedef int32_t type_1_t[E][F];
typedef type_1_t type_2_t[C][D];
for (int i = 0; i < A; i++)
Table[i] = (int32_t*) malloc (sizeof (type_2_t) * dynamic_B);
Using this, I get an error ("error: subscripted value is neither array nor pointer nor vector") when using the table.
XXX = Table [a][b][c][d][e][f];
You've got the wrong type:
int32_t* Table[A];
should be in fact
int32_t (*Table[A])[C][D][E][F];
or, as you typedef'd it
type_2_t *Table[A];
This should do the trick.
Eyes hurt!
Why not declare it as int * * * * * *Table and malloc it in 5 nested for loops? This way you're future proofed if any other dimensions decide to go dynamic :)
Table = malloc(A * sizeof(int *****));
for (i=0; i<A; ++i)
{
Table[i] = malloc(B * sizeof(int ****));
for (i1=0; i1<B; ++i1)
{
...
}
}
Disclaimer: i most likely got the number of indirections wrong.
#define SIZE_B (C*D*E*F*sizeof(int32_t))
int32_t***** Table[A];
or (int i = 0; i < A; i++)
Table[i] = (int32_t*****) malloc ( SIZE_B * dynamic_B);
Edited 2: The code above does absolutely nothing and is complete rubbish. Leaving it as a reminder to check code thoroughly before I post
Edited 3: This works like a charm here, finally :)
#define SIZE_B (C*D*E*F*sizeof(int))
typedef int t2[C][D][E][F];
t2* ar[A];
int dynB = 3;
for(int i=0;i<A;i++)
{
ar[i] = (t2*)malloc(SIZE_B * dynB);
}
精彩评论