Static array with parameter based size?
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 12 06:32:59 PDT 2017
On Wednesday, 12 July 2017 at 05:45:13 UTC, Miguel L wrote:
> void f(int x)
> {
> int[] my_array;
> my_array.length=x;
>
> but I don't really need a dynamic array as length is not going
> to change inside f.
Then just don't change the length... this is a correct way to do
it.
You could also allocate it with `alloca` or `malloc` depending on
exact use.
I also sometimes like to just slice a static array:
```
void f(int x) {
int[1000] buffer;
int[] my_array = x < buffer.length ? buffer[0 .. x] : new
int[](x);
}
```
Which gives the speed benefits of static without putting a size
limit on it.
Just make sure you keep track of ownership with any of these
strategies.
> Also what is it possible in D to write a function that accepts
> an static array of any size?
Best option is to just accept a slice:
void f(int[] x);
and call it like so:
int[123] some_static_array;
f(some_static_array[]);
That will work on any size and typically give best performance.
Again though, just use caution about ownership when using static
arrays.
More information about the Digitalmars-d-learn
mailing list