I have dynamic array in struct and a method that uses the dynamic array. The problem is that I get range violation error when I run the program. However when I create a new dynamic array inside the method, it works fine. The 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, this one works;
struct MyStr {
int[] frontArr;
this(int max = 10) {
frontArr = new int[10];
}
void push(int x) {
frontArr = new int[10]; // <---Add this line
frontArr[0] = x;
}
}
void main() {
MyStr s;
s.push(5);
}
I basically add that line to test the scope. It seems like the initialized FrontArr can't be seen in push(int x) method. Any explanation?
Thanks in advance.