How do I pass a 2D array in C++ to a Fortran subroutine?

前端 未结 3 1581
暖寄归人
暖寄归人 2020-12-29 16:27

I am writing a small C++ program which passes a 2-D array (of complex numbers) to a Fortran subroutine and receives it back filled with values. I wrote a version which passe

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 17:02

    New advice

    A two-dimensional array in c++ is not--I repeat not--the same as a pointer to a pointer{*}!

    When you do

    struct cpx** A;
    

    you are setting up to construct a so called "ragged array" for which there is not a fortran equivalent. You want something like

    struct cpx *A[2][2] = new struct cpx[2][2];
    

    which is a pointer to a two-dimensional array with rows 2 long.

    {*} Yes, you can access a pointer-to-pointer structure using the two-dimensional array notation, but they are laid out differently in memory. ::grumble:: People who tell other people that arrays and pointers are the same thing in c need to meet the Big Foam Clue Bat.

    • A two dimensional array is a single allocation of **sizeof(). It's name decays to a pointer-to-type.
    • A ragged array is 1+ allocation. The one is *) and the other are *sizeof().

    Old, correct, but non-applicable advice

    The thing to be aware of here is that c++ and fortran believe arrays are stored differently in memory.

    C++ thinks that the memory position after a[1][1] is a[1][2], while fortran believes that is is a[2][1]. The distinction is between row-major (c, c++, etc) and column major (fortran, matlab, a few others).

    Note that this is separate from fortran indexing arrays from 1 by default.

提交回复
热议问题