Thread overview
How to refer to different sized static arrays
Feb 08, 2020
Adnan
Feb 08, 2020
Ferhat Kurtulmuş
Feb 08, 2020
Ali Çehreli
February 08, 2020
Just a foreword, this is for learning purposes, hence I am not using the dynamic array or Array!T.

I have a structure that maintains a heap allocated sized array inside.

struct LifoStack(T) {
  T[?] data;
}

This `data` is manually resized and copied. Thus the size itself is not a compile time constant. What should go inside `?` in the the type signature of data?

Also, how can I create runtime-determined sized fixed array in the heap?
February 08, 2020
On Saturday, 8 February 2020 at 08:22:46 UTC, Adnan wrote:
> Just a foreword, this is for learning purposes, hence I am not using the dynamic array or Array!T.
>
> I have a structure that maintains a heap allocated sized array inside.
>
> struct LifoStack(T) {
>   T[?] data;
> }

T[N] is a static array and N must be a compile time constant such as a literal, an enum, or a template parameter. So you cannot change its size. This is the distinct difference between static and dynamic arrays.

> Also, how can I create runtime-determined sized fixed array in the heap?

The heap is for dynamic allocations, I don't understand why to store a fixed-length array in the heap. Why not just to make data dynamic array?
February 08, 2020
On 2/8/20 12:22 AM, Adnan wrote:
> Just a foreword, this is for learning purposes, hence I am not using the dynamic array or Array!T.
> 
> I have a structure that maintains a heap allocated sized array inside.
> 
> struct LifoStack(T) {
>    T[?] data;
> }
> 
> This `data` is manually resized and copied. Thus the size itself is not a compile time constant. What should go inside `?` in the the type signature of data?

You just leave the parentheses empty:

  T[] data;

T[] is internally two things, the equivalent of the following:

   size_t length;
   T * ptr;

> Also, how can I create runtime-determined sized fixed array in the heap?

To have fixed-size array, you have to somehow spell the size out at compile time. The closest thing that comes to mind... does not make sense... :)

T[N] makeStaticArray(T, size_t N)() {
  T[N] result;
  return result;
}

void main() {
  auto arr = makeStaticArray!(int, 42)(); // <-- Must say 42
}

See std.array.staticArray, which is much more useful:

  https://dlang.org/phobos/std_array.html#staticArray

But, really, if the size is known at run time, it's a dynamic array. :)

Ali