I have some C code that I use to calculate the sequential index in memory of a multi-dimensional arrays. It can be used for an arbitrary number of dimensions. Works in row-major order (C language style). Below is a sample snippet of an array of size 2,3:

C row-major order:

index 0 = 0,0

index 1 = 0,1

index 2 = 0,2

index 3 = 1,0

index 4 = 1,1

index 5 = 1,2

// Calculate and store the factors on startup (ahead of time, in constructor)

// This code created with help from:

//

http://www.brpreiss.com/books/opus5/html/page90.html
int nDimensions = 2;

int nDimSize[2] = {2, 3};

int nFactors[2];

int nProduct = 1;

for (int i=nDimensions-1; i>=0; --i) {

nFactors[i] = nProduct;

nProduct *= nDimSize[i];

}

// When array value is specified later, calculate its index and retrieve it

// example: array(1,0) - zero-based

int nIndices[2] = {1, 0};

int nIndex;

for (int i=0; i<nDimensions; ++i) {

nIndex += nFactors[i] * nIndices[i];

}

// Resulting nIndex is 3 (zero-based)

Now my problem is, I have to figure out a similiar way to calculate the index if the array is specified in column-major order. Our application interfaces with FORTRAN code which uses column-major order. So if a multidmensional array is declared and set in FORTRAN, our C app must correctly display those values. Right now, it is not doing so.

Fortran column-major order:

index 0 = 0,0

index 1 = 1,0

index 2 = 0,1

index 3 = 1,1

index 4 = 0,2

index 5 = 1,2

I can't seem to figure out the right function to calculate the 'nFactors' variable, and the 'nIndex' value from that. You'd think it would be just flipping around a couple of things, but I just can't get it to work.

I'd appreciate any help.