数组和指针的形状 [英] Array and pointer shapes

查看:179
本文介绍了数组和指针的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释我为什么下面的程序不能正常工作,以及如何使其工作?
在主程序我分配一个指针,在子程序我找阵列的形状,并得到错误的值。

 程序测试
    真实的,指针,尺寸(:,:,:) :: ARR
    分配(ARR(3,5,7))
    打印*,测试,形状(ARR)
    调用子(ARR)
    打印*,早在测试:形状(ARR)
  结束程序测试  子程序子(ARR)
    真实的,指针,尺寸(:,:,:) :: ARR
    打印*,在子:形状(ARR)
  结束子程序

输出:

 测试:3 5 7
 在子:12694064 1 3
 早在测试:3 5 7

感谢

PS:我使用gfortran(GCC 4.4.3)

编辑:用gfortran 4.6,这code根本不编译。我得到的错误:


  

假人论点过程子的改编在(1)具有一个需要显式接口此过程的属性



解决方案

要使用的Fortran 90/95/2003/2008的高级功能的程序(子程序和函数)的接口应该知道给调用者。这被称为显式接口。 gfortran 4.6告诉你问题是什么。最简单的方法是把一个模块中的程序。试试这个:

 模块mysubs
隐无
包含
  子程序子(ARR)
    真实的,指针,尺寸(:,:,:) :: ARR
    打印*,在子:形状(ARR)
  结束子程序
前端模块mysubs程序测试
    使用mysubs
    隐无
    真实的,指针,尺寸(:,:,:) :: ARR
    分配(ARR(3,5,7))
    打印*,测试,形状(ARR)
    调用子(ARR)
    打印*,早在测试:形状(ARR)
结束程序测试

Can someone explain me why the following program doesn't work, and how to make it work? In the main program I allocate a pointer, in the subroutine sub I look for the shape of the array and get wrong values.

  program test
    real, pointer, dimension(:,:,:) :: arr
    allocate(arr(3,5,7))
    print *, "In test: ",shape(arr)
    call sub(arr)
    print *, "Back in test: ",shape(arr)
  end program test

  subroutine sub(arr)
    real, pointer, dimension(:,:,:) :: arr
    print *, "In sub: ",shape(arr)
  end subroutine

Output:

 In test:            3           5           7
 In sub:     12694064           1           3
 Back in test:            3           5           7

Thanks

PS: I'm using gfortran (gcc 4.4.3)

EDIT: with gfortran 4.6, this code simply doesn't compile. I get the error:

Dummy argument 'arr' of procedure 'sub' at (1) has an attribute that requires an explicit interface for this procedure

解决方案

To use the "advanced" features of Fortran 90/95/2003/2008 the interfaces of procedures (subroutines and functions) should be known to the caller. This is called "explicit" interfaces. gfortran 4.6 told you what the problem was. The easiest way is to put your procedures in a module. Try this:

module mysubs
implicit none
contains
  subroutine sub(arr)
    real, pointer, dimension(:,:,:) :: arr
    print *, "In sub: ",shape(arr)
  end subroutine
end module mysubs

program test
    use mysubs
    implicit none
    real, pointer, dimension(:,:,:) :: arr
    allocate(arr(3,5,7))
    print *, "In test: ",shape(arr)
    call sub(arr)
    print *, "Back in test: ",shape(arr)
end program test

这篇关于数组和指针的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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