Range violation error in the code

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 12 08:37:53 PDT 2011


On Tue, 12 Apr 2011 08:20:20 -0400, Ishan Thilina <ishanthilina at gmail.com>  
wrote:

> I can compile the following code. But when I run the program it gives me  
> a
> "core.exception.RangeError at untitled(34): Range violation
> " error.
>
> The code is as follows.
>
> "
> import std.stdio;
>
> int main(char[][] args)
> {
> 	 struct Node{
> 		int _value;
> 		Node* _next,_prev,_up,_down;
> 	}
>
> 		Node*[]  pointers;
> 		int i=0;
>
> 		auto  n=new Node;
> 		pointers[i]=n;
>
> 	return 0;
> }
>
> "
>
> Here's the error.
>
> "
> core.exception.RangeError at untitled(34): Range violation
> ----------------
> /home/ishan/untitled(onRangeError+0x28) [0x8098a08]
> /home/ishan/untitled(_d_array_bounds+0x16) [0x80968c6]
> /home/ishan/untitled(_D8untitled7__arrayZ+0x12) [0x8094332]
> /home/ishan/untitled(_Dmain+0x35) [0x8094309]
> /home/ishan/untitled(_D2rt6dmain24mainUiPPaZi7runMainMFZv+0x1a)  
> [0x8096a26]
> /home/ishan/untitled(_D2rt6dmain24mainUiPPaZi7tryExecMFMDFZvZv+0x20)  
> [0x80969b8]
> /home/ishan/untitled(_D2rt6dmain24mainUiPPaZi6runAllMFZv+0x32)  
> [0x8096a6a]
> /home/ishan/untitled(_D2rt6dmain24mainUiPPaZi7tryExecMFMDFZvZv+0x20)  
> [0x80969b8]
> /home/ishan/untitled(main+0x94) [0x8096964]
> /lib32/libc.so.6(__libc_start_main+0xe7) [0xf7613ce7]
> /home/ishan/untitled() [0x8094221]
> "
>
> As it seems the problem is with the line "pointers[i]=n". What's wrong  
> here? :s

An array does not dynamically adjust its length when you assign an  
element, you have to assign the length explicitly before-hand.  Some  
dynamic languages do this (like Javascript), but not D.

You can achieve this with an associative array:

Node*[int] pointers;

However, iterating an AA does not guarantee order.  So it depends on your  
requirements.

-Steve


More information about the Digitalmars-d-learn mailing list