# Allocating a pointer to an array of C structs using C FFI

**URL:** <https://racket.discourse.group/t/allocating-a-pointer-to-an-array-of-c-structs-using-c-ffi/3615>\
**Category:** Questions & Answers\
**Tags:** ffi\
**Created:** [March 10, 2025, 3:09pm UTC](https://racket.discourse.group/t/allocating-a-pointer-to-an-array-of-c-structs-using-c-ffi/3615 "2025-03-10T15:09:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jjsimpso](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/jjsimpso/32/602_2.png) [@jjsimpso](https://racket.discourse.group/u/jjsimpso)\
**Post date:** [March 10, 2025, 3:09pm UTC](https://racket.discourse.group/t/allocating-a-pointer-to-an-array-of-c-structs-using-c-ffi/3615/1 "2025-03-10T15:09:12Z")

</div>

I'd like suggestions for improving the following function:

```scheme
(define-cstruct _Slice
  ([start _intptr]
   [end _intptr]
   [stride _intptr]))

;; provide the number of dimensions and a list of triples(start end stride)
;; returns a cpointer to an array of _Slices
(define (make-slice nd range-lst)
  (define slice-ptr 
    (vector->cblock 
     (for/vector #:length nd
                 ([r (in-list range-lst)])
       (apply make-Slice r))
     _Slice))
  (set-cpointer-tag! slice-ptr 'Slice)
  slice-ptr)

```

The `make-slice` function is used to provide an argument to a C function that takes a `Slice *` pointer. The function accepts NULL as a valid argument. This works for my needs, but I have two questions:

1 ) Is there a better way to allocate an array of C structs on the Racket side?

`_fun` has forms to automatically accept vectors and convert them to cpointers but I don't think that will work for NULL pointer arguments.

Is there a better way to do this using `_array`? I couldn't figure out how to use arrays with C structs since `make-Slice` (the function created by `define-cstruct`) returns a pointer to a `_Slice` and not the data. So I can't create an array and set each element with `array-set!`.

2 ) Is there a way to set the cpointer tag automatically? Manually doing it here is a bit awkward, but hopefully correct.

It seems like `vector->cblock` could do it since it knows the type.

Ideas are appreciated! Overall the C FFI is pretty nice and I've been enjoying working with it. But it is a fairly large API and sometimes I get lost in the docs.
