# f_subptr

Return a borrowed rank-one pointer into existing contiguous storage, without
copying or allocating payload.

```fortran
use futile                                  ! or:
use f_subptr_module, only: f_subptr
```

## Signature

Generated from the FYPP documentation stub `doc/generated/f_subptr_doc.f90` (emitted by
`fypp/subptr-doc.fypp` from the same loops as `flib/f_subptr.f90`). In the
signature, `any_intrinsic` is a documentation placeholder: the argument may
be of any intrinsic type, of any Futile [ABI kind](../../f_prec.md#futile-abi-kinds).
The supported combinations are listed under [Supported kinds and ranks]().

### *interface*  f_subptr_module/f_subptr([ptr, ptr_addr, region, size, from, lbound, n, shape])

Return a non-owning rank-one alias, without copying or allocating payload.
Numeric controls count elements and are normalized to f_size_t.
Explicit empty windows are null; implicit whole empty arrays stay associated.
PTR (arrays) / PTR_ADDR (scalar buffer starts) must remain alive.
N, SIZE, SHAPE and REGION are mutually exclusive element-count selectors.
FROM defaults to one; LBOUND sets the rank-one lower bound (default one).
SHAPE supplies a checked product of extents, never a result rank.
Native bounds remapping supplies multidimensional views; guard null results.

* **Options:**
  * **ptr** *[**any_intrinsic* *,* *target,rank 1-7* *]* :: Persistent contiguous `target` or `pointer` array: any intrinsic type, of any Futile [ABI kind](../../f_prec.md#futile-abi-kinds); rank 1–7. Its lower bounds do not affect window offsets.
  * **ptr_addr** *[**any_intrinsic* *,* *target* *]* :: Scalar start of a raw contiguous buffer (not a numeric address): any intrinsic type, of any Futile [ABI kind](../../f_prec.md#futile-abi-kinds). Requires an explicit window; capacity and lifetime are the caller’s responsibility.
  * **region** *[*[*array_bounds*](../../memory.md#f/module_f_malloc/array_bounds) *,* *in* *]* :: Inclusive first/last element offsets, built with `first.to.last`; reversed endpoints give an explicit empty window. Excludes `from`.
  * **size** *[**integer(f_integer|f_size_t)* *,* *in* *]* :: Legacy spelling of `n`; do not supply both.
  * **from** *[**integer(f_integer|f_size_t)* *,* *in* *]* :: One-based element offset in the flattened source (default 1). Kinds: `f_integer`, `f_size_t`.
  * **lbound** *[**integer(f_integer|f_size_t)* *,* *in* *]* :: Lower bound of the rank-one result (default 1); does not change the selection.
  * **n** *[**integer(f_integer|f_size_t)* *,* *in* *]* :: Nonnegative number of selected elements. Without any selector the whole source, or the suffix at `from`, is selected.
  * **shape** (\*) *[**integer(f_integer|f_size_t)* *,* *in* *]* :: Zero to seven nonnegative extents whose checked product is the element count; the result still has rank one.

## Typical calls

Use the source as the first positional argument and keyword window controls.
Legacy positional forms differ between specifics.

```fortran
flat => f_subptr(source)
flat => f_subptr(source, from=offset, n=count)
flat => f_subptr(source, shape=extents)
flat => f_subptr(source, region=first.to.last)
```

### Selector rules

`n`, `size`, `shape` and `region` are mutually exclusive; `region`
cannot accompany `from`. Integer controls accept `f_integer` and
`f_size_t`, including mixed combinations. `region` is built with
`first.to.last` (`.to.` is exported by `futile`).

## Returns

A rank-one pointer with the source’s intrinsic type and kind; character views
preserve the element length. With no explicit selector the extent is the
remaining flattened element count; otherwise it is the selected count.

## Supported kinds and ranks

**1664** specific procedures implement `f_subptr` (generated by FYPP; table emitted by the documentation stub `f_subptr_doc.f90` from the same loops).

| Type (kind)                                                                                                                                                                                    | ranks of `ptr` / `ptr_addr`   | count kinds             | specifics   |
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------|-------------------------|-------------|
| `integer` (f_int8, f_short, f_integer, f_long); `real` (f_simple, f_double, f_long_double); `complex` (f_simple, f_double, f_long_double); `logical` (f_byte, f_logical); `character` (len=\*) | 0-7                           | `f_integer`, `f_size_t` | 128 each    |

## Notes

### Ownership

Writes through the result modify the owner. The owner must outlive every view;
do not pass temporary expressions. Never `deallocate` or `f_free` a view.
Nullify aliases before freeing their owner.

### Contiguity

Noncontiguous array sections are rejected rather than packed into temporary
storage. For zero-size sections of nonempty parents, contiguity can be processor
dependent; whole empty arrays are supported.

### Empty windows

| Request                                                            | Pointer result                                             |
|--------------------------------------------------------------------|------------------------------------------------------------|
| Explicit zero `n` or `size`, zero shape product, or empty `region` | Disassociated (null), including for a scalar buffer start. |
| Whole empty array with no explicit selector                        | Associated zero-size rank-one view; owns no allocation.    |
| `shape` with no entries                                            | One element, because the product of zero factors is one.   |

An associated zero-size view is a valid array argument, including for
[f_memcpy](f_memcpy.md). A null pointer must not be passed as an ordinary assumed-shape
argument or used as a bounds-remapping target. Do not query an empty view’s
first or last element address.

### Bounds and multidimensional views

Native pointer bounds remapping gives a borrowed view its desired rank.
`shape=` validates the selected element count; the bounds on the left of
`=>` determine rank and extents. Use lower and upper bounds on every result
dimension. For an explicit window that may be empty, check `associated`
*before* remapping, even when the requested shape has zero total size: bounds
remapping requires an associated, defined pointer target (see the
pointer-assignment rules in [WG5 N2014](https://wg5-fortran.org/N2001-N2050/N2014.pdf)).

### Errors

Invalid selectors, negative sizes/extents, invalid offsets, capacity violations,
overflow and noncontiguous nonempty sources raise `ERR_INVALID_MALLOC`; the
result is null when the error is caught. A null pointer alone does not
distinguish an error from a valid explicit empty window: inspect the Futile error
status. Raw scalar-source capacities remain the caller’s responsibility.

### Deprecated `f_subptr2`

`f_subptr2` remains a compatibility interface for default-integer rank-one
sources and rank-two results. Use `f_subptr` plus native bounds remapping
instead. No runtime warning is emitted, and it has no empty-window guarantees.

## Examples

All examples are compiled and run by CI (`tests/flib`).

### Flatten and copy

Flattening/copy example, including nondefault owner bounds:

```fortran
  p=>f_subptr(a)
  if (.not.associated(p)) error stop 'whole view'
  if (f_loc(p(1))/=f_loc(a(-2,4))) error stop 'implicit source lower bounds'
  p=>f_subptr(a,size=2_f_size_t,from=2_f_integer,lbound=-1_f_integer)
  p(-1)=123.0_f_double
  if(a(-1,4)/=123.0_f_double)error stop 'mixed count kinds or shallow alias'
  p=>f_subptr(a,2_f_size_t,2_f_size_t,-3_f_size_t)
  if(lbound(p,1)/=-3.or.f_size(p)/=2)error stop 'legacy wide positional call'
  q=>f_subptr(a)
  r=>f_subptr(out)
  call f_memcpy(src=q,dest=r)
  if(any(out/=reshape(a,[6])))error stop 'copy between shallow flat views'
  nullify(p,q,r)
```

### Remap (nonempty)

```fortran
  subroutine check_nonempty()
    integer(f_integer), pointer :: owner(:),table(:,:)
    integer :: i
    owner=f_malloc_ptr(12,id='remap_owner')
    owner=[(i,i=1,12)]
    ! SHAPE selects six elements; the left-hand bounds give the result its rank.
    table(1:2,1:3)=>f_subptr(owner,from=3,shape=[2,3])
    if (any(shape(table)/=[2,3])) error stop 'nonempty shape'
    if (f_loc(table(1,1))/=f_loc(owner(3))) error stop 'first address'
    if (f_loc(table(2,3))/=f_loc(owner(8))) error stop 'last address'
    table(2,3)=-7
    if (owner(8)/=-7) error stop 'view write did not reach owner'
    nullify(table)
    call f_free_ptr(owner)
  end subroutine
```

### Remap (guarded)

Guard an explicit window that may be empty before remapping:

```fortran
  subroutine example_guarded_remap()
    integer(f_integer), pointer :: owner(:),flat(:),table(:,:)
    integer :: rows
    owner=f_malloc0_ptr(6,id='guarded_owner')
    do rows=0,2,2
      flat=>f_subptr(owner,shape=[rows,3])
      ! Never use a disassociated pointer as a bounds-remapping target.
      if (associated(flat)) then
        table(1:rows,1:3)=>flat
      else
        nullify(table)
      end if
      if (rows==0) then
        if (associated(table)) error stop 'explicit empty view must be null'
      else
        table(2,3)=9
        if (owner(6)/=9) error stop 'guarded view write'
      end if
      nullify(table,flat)
    end do
    call f_free_ptr(owner)
  end subroutine
```

### Remap (empty)

Take the implicit whole view of an empty array to get an associated empty
multidimensional view:

```fortran
  subroutine example_empty_remap()
    integer(f_integer), pointer :: owner(:),flat(:),table(:,:),destination(:,:)
    owner=f_malloc_ptr(0,id='empty_owner')
    flat=>f_subptr(owner)
    if (.not.associated(flat)) error stop 'implicit empty view is associated'
    table(1:0,1:3)=>flat
    if (.not.associated(table)) error stop 'remapped empty view is associated'
    if (any(shape(table)/=[0,3])) error stop 'empty result shape'
    destination=f_malloc_ptr([0,3],id='empty_copy_destination')
    ! Associated zero-size views are valid array arguments; no payload is read.
    call f_memcpy(src=table,dest=destination)
    nullify(table,flat)
    call f_free_ptr(destination)
    call f_free_ptr(owner)
  end subroutine
```

## See also

* [f_subptr_str](f_subptr_str.md) – the same windows counted in **characters**, for strings and C buffers.
* [f_memcpy](f_memcpy.md) – copy raw storage, including into a borrowed view.
* [f_memcpy_bytes](f_memcpy_bytes.md) – byte-count copies between scalar buffer starts.
* [f_size](f_size.md) – element count of an owner, to bound `from` / `n` windows.
* `f_malloc_ptr` – allocate a persistent pointer owner for views ([Memory handling](../../memory.md)).
