Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Pointer allocation question

Li_Dong
Beginner
692 Views
Dear all,

I would like to allocate a pointer in the following way:

[fortran]module Mod_Test

    implicit none

    type A
    end type A

    type, extends(A) :: B
        integer i
    end type B

contains

    subroutine AllocateMemory(ptr)
        class(A), intent(inout), pointer :: ptr

        allocate(ptr)

    end subroutine AllocateMemory

end module Mod_Test

program main

    use Mod_Test

    implicit none

    class(B), pointer :: ptr

    call AllocateMemory(ptr)

end program main[/fortran]
That is allocate the actual pointer in type B through a pointer in type A. The output of ifort is

Test1.F90(47): error #6633: The type of the actual argument differs from the type of the dummy argument. [PTR]
call AllocateMemory(ptr)
------------------------^
compilation aborted for Test1.F90 (code 1)

How could I realize such thought?

Thanks very much

dongli

0 Kudos
3 Replies
Li_Dong
Beginner
692 Views
Can it be done via interoperation with C?

dongli
0 Kudos
jimdempseyatthecove
Honored Contributor III
692 Views
Your sketch code is functionally incorrect

Type B extends type A and is a larger object. Your allocation, if it were to work, would have allocated the smaller (NULL object in this case) object A, and returned a pointer to it (cast as an object of type B). IOW the resultant pointer would point to an object that spilled past the allocated memory.

If you really want to do this (and shoot yourself in the foot)you could UNION the two pointer types (or write code to futz with the pointers).

Jim Dempsey
0 Kudos
Li_Dong
Beginner
692 Views
Hi, Jim,
Thank you for your reply! I know it is wrong, but the idea is to isolate the memory allocation from outside. This comes out when I want to create a generic linked list like "list" in STL for C++.
I can also provide the size of type B, and let the subroutine to allocate memory with such size, but the crucial point is that Fortran doesn't support type conversion like C/C++! So the dummy argument in type A can't be pointer, which make it impossible to allocate memory inside the subroutine.
dongli
0 Kudos
Reply