问题
I want to print the following output
*****
****
***
**
*
using recursive subroutine. And my code is as follows:
PROGRAM PS
IMPLICIT NONE
CALL print_star(5, '*')
CONTAINS
RECURSIVE SUBROUTINE print_star(n, star)
INTEGER :: n
CHARACTER(LEN = *) :: star
CHARACTER(LEN = *) :: new_star
IF (n > 1) THEN
new_star = star // '*'
CALL print_star(n - 1, new_star)
END IF
print *, star
END SUBROUTINE print_star
END PROGRAM PS
Then it return error:
CHARACTER(LEN = *) :: new_star
1
Error: Entity with assumed character length at (1) must be a dummy argument or a PARAMETER
If I just avoid defining new_star, and just CALL
CALL print_star(n - 1, star // '*')
then the program works as expected. I wonder what the error is about and how to resolve it?
回答1:
CHARACTER(*) declares an assumed length character object. That means the object takes its length ("assumes it") from something else.
In the case of a CHARACTER(*) declaration for a dummy argument, the length is assumed from the length of the actual argument.
In the case of a CHARACTER(*) constant (a PARAMETER), the length is assumed from the value given to the constant.
From a language concept point of view there is nothing that your variable new_star can assume its length from, at the point at which it is declared. The language rules that result in the error message that you see reflect this.
But you know what the length of new_star needs to be given the logic later in your program - it needs to be one more than the length of the star dummy argument. So you can declare it appropriately:
CHARACTER(LEN(star) + 1) :: new_star
As an alternative, Fortran 2003 introduces deferred length character objects. These are either allocatable or pointer objects, where the length is specified at the time the object is allocated or associated. They are declared using a length specifier of :.
来源:https://stackoverflow.com/questions/25051108/fortran-character-len-only-apply-to-dummy-argument-or-parameter