在Fortran中返回数组的元素访问 [英] Access elements of returned array in Fortran

查看:672
本文介绍了在Fortran中返回数组的元素访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何一次访问一个从函数返回数组的元素?例如,形状()返回一个整数数组。怎样才能比较数组为整数的元素?以下不会编译:

How does one access an element of an array that is returned from a function? For example, shape() returns an array of integers. How does one compare an element of that array to an integer? The following does not compile:

integer :: a
integer, dimension(5) :: b

a = 5
if (a .eq. shape(b)) then
    print *, 'equal'
end if

该错误是:

if (a .eq. shape(c)) then
    1
Error: IF clause at (1) requires a scalar LOGICAL expression

据我了解,这是因为形状(C)返回一个数组。但是,访问数组的元素似乎并不可能像这样:形状(C)(1)

I understand that this is because shape(c) returns an array. However, accessing an element of the array does not appear to be possible like so: shape(c)(1)

现在如果我添加以下两行:

Now if I add these two lines:

integer, dimension(1) :: c
c = shape(b)

...和如果子句改成这样:

if (a .eq. c(1)) then

...然后它的作品。但我真的要声明一个额外的数组变量来保存的返回值形状(),或者是有一些其他的方式来做到这一点?

... then it works. But do I really have to declare an extra array variable to hold the return value of shape(), or is there some other way to do it?

推荐答案

继与形状和逻辑前pressions等处理的答案,一般的回答你的问题如何一次访问数组的元素是从一个函数返回?是

Further to the answers that deal with SHAPE and logical expressions etc, the general answer to your question "How does one access an element of an array that is returned from a function?" is


  • 在分配前pression具有函数引用到一个数组变量,然后索引数组变量。

  • you assign the expression that has the function reference to an array variable, and then index that array variable.

您使用具有函数引用作为实际参数传递给带有虚拟阵列参数的过程,并执行索引你的前pression。

you use the expression that has the function reference as an actual argument to a procedure that takes a dummy array argument, and does the indexing for you.

因此​​,一般的回答你的问题的最后但我真的要声明一个额外的数组变量来保存形状(返回值),或者是有一些其他的方式来做到这一点? 是,你需要声明另一个数组变量,因此没有,没有其他办法。

Consequently, the general answer to your last questions "But do I really have to declare an extra array variable to hold the return value of shape(), or is there some other way to do it?" is "Yes, you do need to declare another array variable" and hence "No, there is no other way".

(注意,合理的优化编译器将避免任何额外的内存需要操作/分配等,一旦他们有数组函数的结果,它实际上只是一个语法问题)。

(Note that reasonable optimising compilers will avoid the need for any additional memory operations/allocations etc once they have the result of the array function, it's really just a syntax issue.)

有关语言设计的这一方面的理由有时归因于需要避免数组函数结果是字符类型的语法歧义和混乱(它们可能被索引和/或substringed - 你怎么知道是什么意?)。其他人认为这是做了这样只是为了激怒C程序员。

The rationale for this particular aspect of language design is sometimes ascribed to a need to avoid syntax ambiguity and confusion for array function results that are of character type (they could potentially be indexed and/or substringed - how do you tell what was intended?). Others think it was done this way just to annoy C programmers.

这篇关于在Fortran中返回数组的元素访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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