Derived type question

I am currently learning derived types. I am not sure why this subroutine does not work:

subroutine type_test(n, x, res)
  integer(8) :: n
  real(8) :: x(n), res
  
  type my_type
    real(8) :: a(n)
    real(8) :: b(n)
  end type
  
  type(my_type) :: y
  
  y%a = 1d0
  y%b = 2d0 
  
  res = sum(x + y%a - y%b) 
end

I have to use allocatable arrays for a and b to make it work.

About Derived-type parameters:

J3/18-007r1 https://j3-fortran.org/doc/year/18/18-007r1.pdf

Example from “Note 1”

TYPE humongous_matrix(k, d)
   INTEGER, KIND :: k = KIND (0.0)
   INTEGER (SELECTED_INT_KIND (12)), LEN :: d
   !-- Specify a potentially nondefault kind for d.
   REAL (k) :: element (d, d)
END TYPE
1 Like

Apart from your wish to learn about derived types, the example code that you showed really does not need any derived types. The subroutine that you displayed could be replaced by

subroutine type_test(n, x, res)
  integer(8) :: n
  real(8) :: x(n), res
!  
  res = sum(x) - n
end

Lacking a statement from you as to what you wish to accomplish with the derived type, we do not know what “does not work” means, and it is difficult to advise you how to “make it work”.

1 Like

I am simply using the made-up subroutine for practice purposes.

It doesn’t work because in array components of a derived type definition you are allowed to use an explicit-shape specification (e.g. a(n:m,i:j)) or a deferred-shape specification (e.g. a(:)). In the explicit-shape case, the Standard says about n,m,i,j

C750 (R740) Each bound in the explicit-shape-spec shall be a specification expression in which there are no references to specification functions or the intrinsic functions ALLOCATED, ASSOCIATED, EXTENDS_TYPE_OF, PRESENT, or SAME_TYPE_AS, every specification inquiry reference is a constant expression, and the value does not depend on the value of a variable.

Your n is clearly a variable, so it cannot be used. The Parameterised Derived Type solution avoids this clause by using an n that is a type parameter, not a variable.

Deferred-shape would work but requires the component array to be ALLOCATABLE or POINTER.

1 Like