C到Fortran推栈功能转换

时间:2019-02-10 02:01:55

标签: fortran stack push

我正在尝试将C代码转换为fortran语言。该代码是推入堆栈的功能。我已经完成翻译并且代码正在运行,但是没有得到所需的输出。 C代码是:

#include <stdio.h>
#include <string.h>
#define MAX 30

char stack[MAX][MAX];
int top = -1;

void push(char str[]){
 if(top != MAX-1){
  strcpy(stack[++top], str);
  printf("test1 : %s\n",stack[top]);
  }
 else{
  printf("Stack overflow : May be invalid prefix expression\n");
 }
}

int main(){

push("abcd");

return 0;
}

我在Fortran中的翻译是:

 program testf1
 implicit none
 integer   :: maximum
 integer   :: top
 character(len=:), allocatable :: i 
 character, dimension(:), allocatable :: stack  

 maximum = 30
 top = 0


 allocate (stack(maximum))
 i=trim('abcd')
 print*,"this is the test ",i," is ", push(i)

 contains 

 function push(str) result(out1)
 character(len=:), allocatable, intent(in)   :: str ! input
 !character(len=:), allocatable, intent(out)  :: out1 ! output
 character, dimension(:), allocatable        :: out1 ! output
 integer :: length

 length = len(str)
 allocate (out1(length))
 if (top .NE. maximum - 1 ) then
     top=top+1
     out1(top)=str
     print*, "testf1 : ", out1(top)
  else
  print*, "Stack2 overflow : May be invalid prefix expression"
 end if 
 end function push

end program testf1

我得到的不是abcd。我怀疑我应该使用子例程代替函数,因为push不应该像在c语言中那样返回值。但是我仍然在努力处理字符串。我的方法正确吗?我还认为,在c中变量声明中存在错误,因为应该有char stack [max]或1维数组,我已经在fortran中解决了这个问题。

1 个答案:

答案 0 :(得分:2)

您的代码没有执行您想要的操作,因为您说的是

out1(top)=str

在您的代码中,基本上是将str的内容分配给out1的最后一个字符,给函数输入'abcd'后,它会产生字符{{1 }}。有很多更好的方法可以实现您想要的,这是现代Fortran中实现它的一种方法:

a

通过Fortran 2008编译器进行编译和运行,可以得到:

! https://stackoverflow.com/questions/54612689/c-to-fortran-push-stack-function-conversion
module Stack_mod

    integer, parameter :: MAX_STACK_SIZE = 30

    type :: JaggedArray_type
        character(:), allocatable :: Record
    end type JaggedArray_type

    type :: Stack_type
        integer :: top = 0
        type(JaggedArray_type) :: Array(MAX_STACK_SIZE)
    contains
        procedure, pass :: push
    end type Stack_type

contains

    subroutine push(Stack,record)
        implicit none
        class(Stack_type), intent(inout)    :: Stack
        character(*), intent(in)            :: record
        if (Stack%top>MAX_STACK_SIZE) then
            write(*,"(*(g0,:,' '))") "Stack2 overflow: May be invalid prefix expression"
        else
            Stack%top = Stack%top + 1
            Stack%Array(Stack%top)%record = record
            write(*,"(*(g0,:,' '))") "this is the test",Stack%top,"is",Stack%Array(Stack%top)%record
        end if 
    end subroutine push

end module Stack_mod

program testf1

    use Stack_mod, only: Stack_type
    implicit none
    type(Stack_type) :: Stack
    call Stack%push("abcd")
    write(*,"(*(g0,:,' '))") "This is from the main program: ", Stack%Array(Stack%top)%record

end program testf1

您可以在这里在线测试:https://www.tutorialspoint.com/compile_fortran_online.php

我希望我不仅在这里回答一个家庭作业问题,而且您正在尝试在StackOverflow上学习一些东西。