On 8/4/25 10:31 AM, Yuao Ma wrote:
Hi all,

I am trying to understand the effect of the lower argument in the c_f_pointer procedure. If I am correct, should the following test case pass?


If FPTR is an array, its shape is specified by SHAPE; the lower
bounds are specified by LOWER if it is present, otherwise each lower bound is equal to 1.

Keep in mind that Fortran arrays are stored in column-major order, meaning that elements in the same column are stored next to each other in memory. A C ptr does not carry this information, so this is why shape and lower bound are needed. Fortran pointers are 'smart' in this way.

I think your test case should pass.

! { dg-do run }
program lower
   use iso_c_binding
   type(c_ptr) :: x
   integer, target :: array(12)
   integer, pointer :: ptr(:, :)
   integer :: myshape(2)
   integer :: mylower(2)

   array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
   x = c_loc(array)
   myshape = [3, 4]
   mylower = [2, 2]

   call c_f_pointer(x, ptr, shape=myshape, lower=mylower)
   if (any(lbound(ptr) /= [2, 2])) stop 1
   if (any(ubound(ptr) /= [4, 5])) stop 2
   if (any(shape(ptr) /= [3, 4])) stop 3
   if (ptr(2, 2) /= 1) stop 4
   if (ptr(4, 5) /= 12) stop 5

end program lower

Thanks,
Yuao

Reply via email to