0

I'm creating a 2D square matrix in Excel VBA

Dim Matrix(0 To Nrows, 0 To Ncols) as double

and then I pass it as argument ByRef to a function library,

My_foo(Matrix(0,0))

which calls a C++ code. In C++ code I want to access the matrix to get values and make other operations. On this purpose, I read these values as 1D array, so I created an index [R*Ncols + C], where R and C are the element position in 2D representation

void _stdcall My_foo(double* M, long Nrows, long Ncols){

double Value;
R = 10;
C = 0;

Value =  M[R*Ncols + C];

}

At this point I expect to find the element having position (10,0), but I find the element (0,10). It seems my matrix is stored with an inverted column/rows order.

It would be enough to set an index like [C*Nrows + R], and access it by column. I tried this and it works, but it contradicts many blogs and posts...

Why? Is it normal?

Community
  • 1
  • 1
M.Bolzoni
  • 59
  • 3
  • Possible duplicate of [Map a 2D array onto a 1D array C](http://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c) – cbuchart May 12 '17 at 12:29

1 Answers1

0

While C/C++ uses a row-major format to represent multi-dimensional arrays, for other languages different choices were made, so it is not very surprising that Excel VBA uses a column-major format like it is also documented in this forum question.

Gert Wollny
  • 529
  • 2
  • 8
  • Thank you. I didn't know... Does my Matrix, created and populated in excel, maintain its column-major property also in C++? It would explain many things in my code... And what about SAX/VB? My idea is to test some routines in excel and then apply in other SAX/VB environment. – M.Bolzoni May 12 '17 at 12:08
  • @M.Bolzoni It is of course implementation dependent how data is stored in memory and passed around, but I would assume that the layout is not changed when the data is sent to some C++ function (performance wise it wouldn't make sense). Just to give you an example from another language: Python numpy can allocate an [multi-dimensional array](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) with C-layout (row major) or with Fortran layout (column major). As for SAX/VB, I have no idea. – Gert Wollny May 12 '17 at 16:34