如何为矩阵分配内存?

时间:2015-03-25 16:01:07

标签: memory-management matrix fortran

我想为一个用Fortran 90填充双元素的矩阵分配内存,下面是相应的C代码:

int dim = 1024;
double *M = (double *)malloc(dim*dim*sizeof(double));

我在下面编写了代码,但无法使用M(i)访问i>=100

program matrix
INTEGER :: i,d
CHARACTER(len=32) :: arg
REAL*8 M(*)
POINTER(ptr_M, M)

d=0
if(iargc() == 1) then
    call getarg(1, arg)
    read(arg, '(I10)') d
end if
print '("Dimension=", i6)', d

!allocate and init matrix
ptr_M = malloc(d*d*8)
do i=1,d*d
    M(i) = i
end do

print '("M(i)=", f7.4)', M(100)
call free(ptr_M)

end program matrix

出了什么问题?


感谢所有人,这是我的最终解决方案:

program matrix
IMPLICIT NONE
REAL, ALLOCATABLE :: M(:,:)
INTEGER :: i, j, d
CHARACTER(len=32) :: arg

!specify dimension with programm parameter
if(iargc() == 1) then
    call getarg(1, arg)
    read(arg, '(I10)') d
end if

!create and init matrix
ALLOCATE (M(d, d))
do i=1,d
    do j=1,d
        M(i, j) = (i - 1)*d+j
        write (*,*) "M(",i,",",j,")=",M(i, j)
    end do
end do
DEALLOCATE (M)

end program matrix

1 个答案:

答案 0 :(得分:2)

使用ALLOCATABLE数组,您可以按如下方式分配100行和200列的矩阵:

program xalloc
real, allocatable :: x(:,:)
allocate(x(100,200))
end program xalloc