arrays - Error: range violation in D programming -
i have dynamic array in struct , method uses dynamic array. problem range violation error when run program. when create new dynamic array inside method, works fine. following code causes problem.
struct mystr { int[] frontarr; this(int max = 10) { frontarr = new int[10]; } void push(int x) { frontarr[0] = x; } } void main() { mystr s; s.push(5); } however, 1 works;
struct mystr { int[] frontarr; this(int max = 10) { frontarr = new int[10]; } void push(int x) { frontarr = new int[10]; // <---add line frontarr[0] = x; } } void main() { mystr s; s.push(5); } i add line test scope. seems initialized frontarr can't seen in push(int x) method. explanation?
thanks in advance.
initialization of structs must guaranteed. not want default construction of struct throw exception. reason d not support default constructors in structs. imagine if
mystr s; resulted in exception being thrown. instead d provides own default constructor initializes fields init property. in case not calling constructor , using provided defaults means frontarr never initialized. want like:
void main() { mystr s = mystr(10); s.push(5); } it should compiler error have default values parameters of struct constructor. bugzilla
Comments
Post a Comment