问题描述
(我使用了ifort 19.0.5.281)
在以下测试代码中,在#include <stdio.h>
#include <stdlib.h>
typedef struct test_T {
int count1;
int count2;
int *array1;
int *array2;
int check;
} test_T;
int main() {
#define DATA_COUNT 8
int data[DATA_COUNT] = { 2,3,20,21,30,31,32,100 };
test_T *s_t = malloc(sizeof(*s_t));
s_t->count1 = DATA_COUNT;
s_t->count2 = DATA_COUNT;
s_t->array1 = malloc(sizeof(int) * s_t->count1);
s_t->array2 = malloc(sizeof(int) * s_t->count2);
s_t->check = 100;
for (int i = 0; i < DATA_COUNT; i++) {
s_t->array2[i] = s_t->array1[i] = data[i];
}
printf("%d\n",s_t->check);
return 0;
}
中,我将POINTER用作INTENT(IN)并检查其关联状态,并将其关联更改为局部变量move_association
。
array(4,4)
乍一看,我认为应该有一些问题,因为Fortran会在其末尾自动取消分配子例程的局部变量,从而使module mod_test
implicit none
contains
subroutine write_matrix_2d(a)
implicit none
real,intent(in) :: a(:,:)
! local variables
integer :: i,j
do i = lbound(a,1),ubound(a,1)
write(*,*) ( a(i,j),j = lbound(a,2),2) )
enddo
end subroutine
(*) subroutine move_association(a)
implicit none
real,pointer,intent(inout) :: a(:,:)
! local
real,target :: array(4,4)
array = -1
if ( associated(a) ) then
print *,"POINTER is associated"
a => array
else
print *,"POINTER is NOT associated"
a => array
endif
end subroutine
end module
program test
use mod_test
implicit none
real,dimension(3,3),target :: ct(3,3)
real,dimension(:,:),pointer :: cptr(:,:)
ct = 1
!cptr => ct(2:3,2:3)
write(*,*)
write(*,*) 'ct'
call write_matrix_2d(ct)
write(*,*) 'cptr before'
call write_matrix_2d(cptr)
write(*,*)
(*) call move_association(cptr)
write(*,*) 'cptr after'
call write_matrix_2d(cptr)
write(*,*)
if ( associated(cptr) ) then
print *," cptr associated "
else
print *," cptr not associtated "
endif
end program
失去目标。但是cptr
意外地幸免了下来,并且其关联状态也被检查为“ associated”,如以下输出所示。
cptr
我想可能还有其他规则,例如子例程中的本地 ct
1.000000 1.000000 1.000000
1.000000 1.000000 1.000000
1.000000 1.000000 1.000000
cptr before
POINTER is NOT associated
cptr after
-1.000000 -1.000000 -1.000000 -1.000000
-1.000000 -1.000000 -1.000000 -1.000000
-1.000000 -1.000000 -1.000000 -1.000000
-1.000000 -1.000000 -1.000000 -1.000000
cptr associated
变量会自动获得target
属性,以此类推,对吗?
解决方法
末尾的指针状态为undefined
。不允许查询状态未定义的指针的关联状态,它包含一些垃圾。垃圾恰好是不再有效的本地数组。您必须先使其无效或将其自己关联,然后再进行进一步的查询。