www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to refer to different sized static arrays

reply Adnan <relay.public.adnan outlook.com> writes:
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?
Feb 08 2020
next sibling parent Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
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?
Feb 08 2020
prev sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 2/8/20 12:22 AM, Adnan wrote:
 Just a foreword, this is for learning purposes, hence I am not using th=
e=20
 dynamic array or Array!T.
=20
 I have a structure that maintains a heap allocated sized array inside.
=20
 struct LifoStack(T) {
  =C2=A0 T[?] data;
 }
=20
 This `data` is manually resized and copied. Thus the size itself is not=
=20
 a compile time constant. What should go inside `?` in the the type=20
 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=20 compile time. The closest thing that comes to mind... does not make=20 sense... :) T[N] makeStaticArray(T, size_t N)() { T[N] result; return result; } void main() { auto arr =3D 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
Feb 08 2020