I'm looking for a shortcut for 2 and 3 dimensional indexing of arbitrary values, and I know this works for a given array a[]
#define a(i,j,k) a[(i)*span*span+(j)*span+(k)]
#define b(i,j) b[(i)*span+(j)]
But I don't understand how to 开发者_如何学JAVAallow these macros to operate on arbitrary arrays eg;
x(i,j,k)
Anyone care to clue me in?
Don't define the macro name to a or b, instead, give the array as parameter:
#define arr3d(a,i,j,k) a[(i)*span*span+(j)*span+(k)]
#define arr2d(b,i,j) b[(i)*span+(j)]
Then a and b will be parameters and you'll be able to use it for different arrays.
Edit
For example: char newarr[5][5][5]; arr3d(newarr, 3, 3, 3);
also, if span is not a variable defined in all scopes where you need to use this macro, it will not work, and you'll need to add another parameter to the macro - span, so the macro definition will look like:
#define arr3d(a,i,j,k,span) a[(i)*(span)*(span)+(j)*(span)+(k)]
And yes, I would usually avoid this.
get your compiler to preprocess the macros without compiling them to debug macros.
gcc -E -P for gcc.
This macro will expand anything of the form a(i,j,k) into the form a[(i)*span*span+(j)*span+(k)]. It doesn't specifically use those values (by expecting them to be variables), however.
Thus, if you use x(i,j,k), it will replace all as in the macro with xs.
As it looks your dimension span seems to be a compile time integer constant? Then you just shouldn't use a macro. If you use
double A[span][span][span] = { 0 };
or similar, where
#define span 42
or
enum { span = 42 };
indexing in C with A[i][j][k] will work out of the box and do the right thing. Don't complicate your life with an opaque macro for such cases.
加载中,请稍侯......
精彩评论