简体   繁体   中英

How to pass a array of string from fortran to c?

I want to pass a array of string which I filled in fortran code to C. However, every times I tried to check the result I found that each one of the character string is printed as a whole array in C. Can anyone help through this? This is fortran part of code:

        SUBROUTINE hello (Characters)
CHARACTER*(16)  Characters(5)
Characters=(/"ABCD","BCDF","CVFG","D HG","J67F"/)
return
END

and this is C code:

    void hello_(char *[16]);
    int main(int argc,char **args)
    {
    char        Character2[5][16];
    int         j;
    hello_(&Character2);
    for(j=0;j<5;j++){
    printf("String [ %d ] = %s \n",j,Character2[j]);
    }
    return 0;
    }

The results I get is this:

 String [ 0 ] = ABCD            BCDF            CVFG            D HG                  J67F            `����U 
 String [ 1 ] = BCDF            CVFG            D HG            J67F            `����U 
 String [ 2 ] = CVFG            D HG            J67F            `����U 
 String [ 3 ] = D HG            J67F            `����U 
 String [ 4 ] = J67F            `����U  

I want to know why I can't access to each one of those strings which I passed from fortran to C? I mean, how can I make sure that ,like, Character2[1] is exactly what I made in fortran, "ABCD"! Thanks

Since the FORTRAN strings are not NUL terminated, the C code will not be able to detect the end of the string being printed.

Since your strings are meant to be no longer than a certain length, you can specify that in your print statement (although, it is unclear to me that FORTRAN will fill with spaces if you don't provide a long enough string):

printf("String [ %d ] = %.4s \n",j,Character2[j]);

If your FORTRAN code knows it will be called from C, then it should add the NUL byte to the strings before returning the array back to the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM