FORTRAN语言C,分配到串空间装饰效果 [英] Fortran to C , effect of trim on space allocated to string

查看:93
本文介绍了FORTRAN语言C,分配到串空间装饰效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Fortran子程序调用C函数。其中一个参数传递给C函数是Fortran字符串。这被初始化为长度为512字节一个空字符串,并传递给C函数为修剪(STR)// CHAR(0),也就是说,它是修剪和 \\ 0 追加,因此C认为其的strlen 0。

I have a Fortran subroutine that calls a C function. One of the arguments to the C function is a fortran string. This is initialized as an empty string of length 512 bytes, and is passed to the C function as trim(str)//char(0) , i.e. it is trimmed and a \0 is appended so that C sees its strlen as 0.

character(len=512)  :: str = ""
call C_foo (  trim(str)//char(0)  )

现在的C函数里面,
我能做到这一点。

Now inside the C function, can I do this

strncpy (str, "something", strlen("something") )

我想知道的是,因为修剪是在其的文档,它传递到C实际上改变分配给它的空间?里面的C函数,将一个函数strncpy任何故障(只要源字符串&LT的长度; 512)?我试了一下,它工作正常,但我想,以确保它是安全的。

What I want to know is that since trim is a transformational function as mentioned in its docs , does passing it to C actually alter the space allocated to it? Inside the C function, will a strncpy ever fail (as far as length of source string < 512) ? I tried it and it works fine, but I want to be sure it is safe.

推荐答案

详细阐述了我的意见,没有得到成什么C确实,认为这纯粹FORTRAN例如:

elaborating on my comment, without getting into what "C" does, consider this pure fortran example:

character(len=512) :: g=""
call f(trim(g))
end

subroutine f(s)
character(len=*) :: s
integer :: i
do i=1,100
 s(i:i)="0"
enddo
end

这编译罚款,但赛格故障,而只是

This compiles fine but seg faults, while just

call f(g)

就好了。另外,如果我们分配克至是一个足够长的非空字符串,如添加

is just fine. Alternately if we assign g to be a sufficiently long nonblank string, eg add

g(100:100)="0"

它的工作原理很好。

it works a well.

你所看到的是修剪通过()将字符串只需要的长度(它是一个零在第一种情况下),或者1如果添加// CHAR(0))

what you see is the string passed by trim() has only the required lenght (which is zero in the first case), or 1 if you add //char(0) )

顺便说一句简单的赋值在子程序

Incidentally a simple assignment in the subroutine

s=" ... 512 characters .. "

works..assiging只然而,许多字符将适合在所提供的空间。
有趣的是,(gfortran)莫名其妙地知道多少空间来填补..但我不会指望它。

works..assiging only however many character will fit in the supplied space. Interesting that (gfortran) somehow knows how much space to fill.. but I wouldnt count on it.

这篇关于FORTRAN语言C,分配到串空间装饰效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆