What is of interest is that Fortran includes metadata in its internal symbol tables that C doesn't have access to. So you can't write the C arrays as a[i][j], as this symbol metadata never traversed the language barrier. You have to do pointer arithmetic. Notice how it is done.

Post navigation

4 thoughts on “So here is the fortran90 with C problem”

You didn’t already know that? Seriously? You never checked any code that crosses Fortran and C/C++, like GNU Octave, Cactuscode, etc.? Or any of the BLAS implementations in C that are called from LAPACK (and hence can be called with an ALLOCATABLE array from one level up)?

A[i][j] in C means find the ith pointer in the array addressed by A and then the jth element in the array of that pointer. It’s not a multidimensional array. Nothing to do with symbol tables. If you declare int A[2][3];, the compiler acts differently, yes. That’s an inherited legacy that does not play well with the rest of the language.

If you follow a convention of X and ldX for naming the array and the leading dimension, try #define AREF(A,i,j) (A)[i + j * LDNAME(A)] and #define LDNAME(A) ld##A. You need the second expansion (LDNAME) to force name expansion if you pass a macro as AREF’s A argument. Then just AREF(A, i, j) throughout, and &AREF(A, i, j) works as expected.

No I knew about the differences between C and Fortran indexing arrays … its a simple polynomial evaluation, and I just finished coding it into some inline-able functions to make the debugging easier. I also know quite well that a[2][3] is not the same as *(a + 2*lda +3) in a general sense, if a has been built as a pointer array to pointers.

Fortran doesn’t do this. There they try to allocate one big contiguous memory region for the array. Tends to make optimizations easier at the compiler level.

Been using LINPACK/EISPACK since the late 80s, and LAPACK more “recently” (early 90s). Did this as functions rather than macros for the moment. Easier to debug the functions …

Everything is “working” though we are now getting a huge array that looks like it was allocated on the heap rather than the stack, and hitting a segv as soon as we try to index it … which is very strange, as I print values from this array previously in this same routine.

It looks like it uses a simple rule. If the allocation is below some (fixed) size, it happens on the stack, otherwise it happens in heap. gcc/gfortran and the intel compilers let you play with this a little.

What I have found more recently is a need to use the mcmodel=medium options in compilers rather than the default (small). This is a data size issue, if your data is larger than 4GB of ram, you need this.