将值分配给传递给函数的变量会导致分段错误. [英] Assigning a value to a variable passed to a function causes a segmentation fault.
问题描述
考虑以下简单程序:
program foo
integer bar,idum
print * , bar(1)
end program
function bar(idum)
integer idum,bar
print * , idum
idum = 2
bar = 2
return
end
运行它时,在行idum = 2
Starting program: /tmp/a.out
1
Program received signal SIGSEGV, Segmentation fault.
0x000000000040081b in bar (idum=1) at play.f:11
11 idum = 2
我不允许将值分配给传递给函数的变量吗?如何将它们用作标志?
Am I not allowed to assign values to variables passed to a function? how can I use them as flags?
推荐答案
您将文字值1
传递给函数.然后您尝试在其中更改
You pass a literal value 1
to the function. Then you try to change it in
idum = 2
那是不允许的.该代码尝试更改文字常量并崩溃,因为这是不可能的.
That is not allowed. The code tries to change the literal constant and crashes, because that is not possible.
如果要更改函数内部的值,则a)它必须是变量,而不是常量值,b)必须按值传递(Fortran 2003).
If you want to change a value inside a function, then a) it must be a variable, not a constant value, b) it must be passed by value (Fortran 2003).
在现代Fortran中,始终始终使用显式接口.我的意思是总是.使用模块(首选!!),或者在简单情况下,使用内部函数,如:
In modern Fortran always use explicit interfaces. I mean ALWAYS. Either use modules (preferred!!!), or, in simple cases, use internal functions like:
program foo
integer bar,idum
print * , bar(1)
contains
function bar(idum)
integer idum,bar
print * , idum
idum = 2
bar = 2
return
end function
end program
编译器可能会告诉您您做错了.尤其是这样,如果您为参数指定intent
:
The compiler may be able to tell you you are doing it wrong. Especially so, if you specify intent
for the argument:
function bar(idum)
integer bar
integer, intent(in) :: idum
编译器将现在抱怨.它还会出于其他意图而抱怨.然后,您可以修复代码以使编译器满意.
The compiler will complain now. It will also complain with other intent's. And you can then fix the code to make the compiler happy.
然后总是!!!!! 使用IMPLICIT NONE
.这不是可选的.有必要.
And ALWAYS!!!!! use IMPLICIT NONE
. This is not optional. It is necessary.
这篇关于将值分配给传递给函数的变量会导致分段错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!