Thread overview | |||||
---|---|---|---|---|---|
|
February 25, 2017 [Beginner]Variable length arrays | ||||
---|---|---|---|---|
| ||||
I am trying to create an array which has a user defined size. However the following program is not compiling: import std.stdio; void main(){ write("Enter your array size: "); int n; readf(" %s", &n); int[n] arr; //<-Error: variable input cannot be read at compile time writeln(arr); } 1. What's causing this? 2. How can I get around this? I know I can always create a loop that appends value 'n' times. |
February 26, 2017 Re: [Beginner]Variable length arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to helxi | On 26/02/2017 3:31 AM, helxi wrote: > I am trying to create an array which has a user defined size. However > the following program is not compiling: > > import std.stdio; > > void main(){ > write("Enter your array size: "); > int n; > readf(" %s", &n); > int[n] arr; //<-Error: variable input cannot be read at compile time > writeln(arr); > } > > 1. What's causing this? T[X] is a static array, its size must be known at compile time. Static arrays are passed around by value not by reference and generally get stored on the stack not the heap. > 2. How can I get around this? I know I can always create a loop that > appends value 'n' times. This is where you want a dynamic array, allocated on the heap at runtime. T[] array; array.length = n; |
February 25, 2017 Re: [Beginner]Variable length arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to rikki cattermole | On Saturday, 25 February 2017 at 14:34:31 UTC, rikki cattermole wrote:
> On 26/02/2017 3:31 AM, helxi wrote:
>> I am trying to create an array which has a user defined size. However
>> the following program is not compiling:
>>
>> import std.stdio;
>>
>> void main(){
>> write("Enter your array size: ");
>> int n;
>> readf(" %s", &n);
>> int[n] arr; //<-Error: variable input cannot be read at compile time
>> writeln(arr);
>> }
>>
>> 1. What's causing this?
>
> T[X] is a static array, its size must be known at compile time.
> Static arrays are passed around by value not by reference and generally get stored on the stack not the heap.
>
>> 2. How can I get around this? I know I can always create a loop that
>> appends value 'n' times.
>
> This is where you want a dynamic array, allocated on the heap at runtime.
>
> T[] array;
> array.length = n;
Thanks
|
Copyright © 1999-2021 by the D Language Foundation