digitalmars.D.learn - Static array with parameter based size?
I need to create a non-dynamic array like this
void f(int x)
{
int[x] my_array;
...
this does not compile as x value needs to be known at compile
time. The closest to this I can get is:
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.
What is the best way to do this?
Thanks in advance
Jul 11 2017
Miguel L wrote:
I need to create a non-dynamic array like this
void f(int x)
{
int[x] my_array;
...
this does not compile as x value needs to be known at compile time. The
closest to this I can get is:
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.
What is the best way to do this?
Thanks in advance
for simple cases you can use `alloca()`. it is fairly low-level, but does
it's job.
but if your array is really big, or contains types with dtors, you'd better
stick with `new` (or setting length). you can also put `scope(exit) delete
my_array;` after declaration, so array will be destroyed on function exit.
`delete` is... slightly deprecated ;-) (i.e. not recommented for wide use),
but works, and will call dtors for you.
Jul 11 2017
On Tuesday, 11 July 2017 at 08:23:02 UTC, Miguel L wrote:
I need to create a non-dynamic array like this
void f(int x)
{
int[x] my_array;
...
this does not compile as x value needs to be known at compile
time. The closest to this I can get is:
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.
What is the best way to do this?
Thanks in advance
Another approach would be to use a template function:
----
void f(int x)()
{
int[x] array;
}
void main()
{
f!42;
}
----
Jul 11 2017









ketmar <ketmar ketmar.no-ip.org> 