Cricket
Cricket

Reputation: 491

How to allocate memory for a matrix?

I want to allocate memory for a matrix filled with double elements with Fortran 90, below is the corresponding C code:

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

I wrote the code below but I could not access M(i) with 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

what's wrong?


Thanks to all, here is my final solution:

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

Upvotes: 1

Views: 236

Answers (1)

Fortranner
Fortranner

Reputation: 2605

Using an ALLOCATABLE array, you can allocate a matrix with 100 rows and 200 columns as follows:

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

Upvotes: 2

Related Questions