主题:请高手帮忙看看这个程序为什么会数组越界?
lockheed123
[专家分:0] 发布于 2011-04-23 11:12:00
主程序
------------------------------------------------
program main
use array
implicit none
integer,allocatable::a(:)
integer::num
integer::i
call arrayin(a,num)
write(*,*) num
do i=1,num
write(*,*) a(i)
end do
end program main
----------------------------
子程序
----------------------------
module array
contains
subroutine arrayin(a,num)
implicit none
integer::num
integer,allocatable::a(:)
integer::i
write(*,*)"input the length of the array"
read(*,*) num
allocate(a(1:num))
write(*,*)"input each element of the array"
do i=1,num
read(*,*) a(i)
end do
end subroutine
end module
--------------------------------------------------
这只是个示例。比如输入num=3,然后输入三个数,最后输出时确实数组越界,请问高手为什么会这样。
回复列表 (共46个回复)
沙发
fortkonglone [专家分:70] 发布于 2011-04-23 12:40:00
单就你发上来的程序,没问题。我为了确认,特意用ifort编译运行验证过,没任何毛病。建议把具体的编译信息放上来。
板凳
asymptotic [专家分:16630] 发布于 2011-04-23 16:52:00
楼主和一楼热心网友皆要加强 Fortran 语言的学习,修炼基本功很重要。
3 楼
lh_wp [专家分:100] 发布于 2011-04-23 17:02:00
[quote]楼主和一楼热心网友皆要加强 Fortran 语言的学习,修炼基本功很重要。[/quote]
你光说人家,也不说为啥,哈哈
主程序里面也应allocate
4 楼
lockheed123 [专家分:0] 发布于 2011-04-23 17:41:00
可是主程序里num开始是未知的,怎么allocate呢?
5 楼
lh_wp [专家分:100] 发布于 2011-04-23 18:34:00
既然用到了模块,把这个数组及其长度放在模块头部,完后当作全局变量用就行
6 楼
fortkonglone [专家分:70] 发布于 2011-04-23 19:41:00
[quote]楼主和一楼热心网友皆要加强 Fortran 语言的学习,修炼基本功很重要。[/quote]
既然用了这样的口吻,就请把原因说清楚。这样轻飘飘一句话,只会让人反感,没人会觉得你高明。
我不想指责你顺口开河,也不想指责你回帖不看贴。如回帖所说,我是真的编译运行过的:
tem.f90:
--------------------------------------------------
module array
contains
subroutine arrayin(a,num)
implicit none
integer::num
integer,allocatable::a(:)
integer::i
write(*,*)"input the length of the array"
read(*,*) num
allocate(a(1:num))
write(*,*)"input each element of the array"
do i=1,num
read(*,*) a(i)
end do
end subroutine
end module
program main
use array
implicit none
integer,allocatable::a(:)
integer::num
integer::i
call arrayin(a,num)
write(*,*) num
do i=1,num
write(*,*) a(i)
end do
end program main
结果:(环境:ubuntu10.04 32bit ; ifort 2011 XE)
--------------------------------------------------
$ifort tem.f90
$./a.out
input the length of the array
3
input each element of the array
1
5
9
3
1
5
9
7 楼
lockheed123 [专家分:0] 发布于 2011-04-23 19:43:00
谢谢。我之前是用cvf编译出错的,现在我又用ivf试了一下,发现没错。看来这跟编译器也有关系。
我是新手,之前把彭国伦写的《fortran95程序设计》看了几遍。现在又听人说fortran95的标准落后了。请问能不能推荐一两本讲比较新的fortran标准的书?
8 楼
fortkonglone [专家分:70] 发布于 2011-04-23 19:48:00
[quote][quote]楼主和一楼热心网友皆要加强 Fortran 语言的学习,修炼基本功很重要。[/quote]
你光说人家,也不说为啥,哈哈
主程序里面也应allocate[/quote]
楼主贴出来的程序在语法上本没问题,我自己亲身编程,实地运行,验证过了。我怀疑是其他因素,所以才要求他把编译信息贴上来。
主程序不必重复用allocate,直接调用子过程就是。我实验时出过的唯一一次编译错误,是因为偷懒没用module,只用了subroutine,忘了如果这样就没有显式借口了,会编译出错。
9 楼
lh_wp [专家分:100] 发布于 2011-04-23 19:50:00
Fortran95/2003程序设计。
10 楼
fortkonglone [专家分:70] 发布于 2011-04-23 19:55:00
[quote]谢谢。我之前是用cvf编译出错的,现在我又用ivf试了一下,发现没错。看来这跟编译器也有关系。
我是新手,之前把彭国伦写的《fortran95程序设计》看了几遍。现在又听人说fortran95的标准落后了。请问能不能推荐一两本讲比较新的fortran标准的书?[/quote]
你可以在论坛上翻一翻我写的Fortran入门三部曲。其实,F95不落后,新标准的新特性反而用得不多,起码在我们学校,还有很多实验室停留在F77的层次呢……
我来回复