Dynamic array and foreach loop

DarthCthulhu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 8 10:19:07 PDT 2015


On Saturday, 8 August 2015 at 15:57:15 UTC, Binarydepth wrote:
> Here's what happens :
>
> How many elements need to be used? 5
> Input the element : 1 1
> Input the element : 1 2
> Input the element : 1 3
> Input the element : 1 4
> Input the element : 1 5
> How many positions do you wish to rotate ? 3
> The original patter is : 5 0 0 0 0
> The final is : 0 0 0 5 0
> Do you want to rotate again ? y/n y
> How many positions do you wish to rotate ? 2
> The original patter is : 0 0 0 5 0
> The final is : 5 0 0 0 0
> Do you want to rotate again ? y/n n
> Do you want to make an adicional  sequence ? a/A a
> How many elements need to be used? 4
> Input the element : 1 1
> Input the element : 1 2
> Input the element : 1 3
> core.exception.RangeError at gen014.d(31): Range violation
> ----------------
> 0x4077ef _Dmain
> 	???:0
> 0x41684e void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).runAll().void __lambda1()
> 	../../../../src/libphobos/libdruntime/rt/dmain2.d:408
> 0x416abe void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).tryExec(scope void delegate())
> 	../../../../src/libphobos/libdruntime/rt/dmain2.d:383
> 0x416d18 void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).runAll()
> 	../../../../src/libphobos/libdruntime/rt/dmain2.d:408
> 0x416abe void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).tryExec(scope void delegate())
> 	../../../../src/libphobos/libdruntime/rt/dmain2.d:383
> 0x416c45 _d_run_main
> 	../../../../src/libphobos/libdruntime/rt/dmain2.d:416
> 0x7f8c84eeda3f __libc_start_main
> 	???:0
> 0x406058 _start
> 	???:0
> 0xffffffffffffffff ???
> 	???:0

This is happening because 'num' is reading the value of each 
element in the array; it's not a count. Once it reads the 5 in 
element, it attempts to put the next number into element 5, which 
of course doesn't exist.

This is also why the first time through there is only one value 
in the array that isn't 0: 'num' the first time through is always 
zero because the values of the dynamic array are .init-ed to zero.

You can fix it like the following:

foreach(num, element; liaOrig)	{//Data input loop
		
			writefln("num: %s current element: %s liaOrig.length: %s", 
num, element, liaOrig.length);

			write("Input the element : ", num+1, " ");
			readf(" %d", &liaOrig[num]);
		}

Now 'num' is just an iterative number starting from 0 (the .init 
value of an int), while the actual element value is  stored in 
'element'. I added the writefln() statement to make it a bit more 
clear during runtime.

As an addenum, you don't need the liaOrig[0 .. $] in the foreach 
statement; just the name of the array variable is required to 
walk the entire array.

Hope this helps!


More information about the Digitalmars-d-learn mailing list