0

I'm trying to define a macro to convert 2D array syntax to 1D vector. i.e., for a 12x12 array, matrix[i,j] should evaluate to matrix[12*i + j]. So far I have tried

#define matrix[i,j] matrix[12*i+j]

#define (matrix[i,j]) matrix[12*i+j]

#define matrix[(i,j)] matrix[12*i+j]

#define matrix([i,j]) matrix[12*i+j]`

The reason I am using matrix[i,j] syntax is because it will be an extension to be called from R code, and I would like the other authors of the project to understand exactly what is being done. Is there a way to do this with a macro?

4
  • 2
    Why a macro? I would think this is function territory, esp. if you're talking about exposing it to something else. Remember macros are pre-processor time only. Commented Feb 8, 2013 at 15:16
  • Don't use macros. They are evil. Commented Feb 8, 2013 at 15:35
  • 1
    Why are you even doing that? What's wrong with the normal [][] syntax? Commented Feb 8, 2013 at 16:08
  • 1
    I rather suspect that "other authors" will be more, not less, confused if you take this approach. Why aren't you creating your data objects as matrices in the first place? Commented Feb 8, 2013 at 16:54

3 Answers 3

1

Something like this may work:

#define TO_1D(m,x,y) (m[x*12+y])

int matrix[100];
TO_1D(matrix, 0, 4) = 13;

but I wonder why you don't prefer something safer like:

int data[100];
inline int& matrix(int x, int y)
{
   return data[x*12+y];
}
Sign up to request clarification or add additional context in comments.

Comments

1

The only way that you can do is with ( ) and not with []

#define matrix(i,j) matrix[12*i+j]

and in the code, you define matrix in this way

int matrix[12*12];
matrix(i,j) = 5;

3 Comments

How can that work. The macro will expand both instances of matrix.
I checked with gcc -E and no problemwith that
Code generated with gcc -E: int main() { int matrix[12*12]; matrix[12*1 +1] = 15; }
1

It would be better to only define a macro for the calculation, not the dereferencing.

#define X_DIM 12
#define Y_DIM 12
#define D21(x,y) (X_DIM*(x)+(y))

int my_matrix1[X_DIM*Y_DIM];
double my_matrix2[X_DIM*Y_DIM];

my_matrix1[D21(4, 3)];
my_matrix2[D21(2, 1)];

So you are not limited to the unique matrix defined in your macro.

More fundamentally, why are you even trying to do that? The normal multidimensional array syntax is already there to do exactly that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.