Error: range violation in D programming
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 p开发者_运维技巧rogram. 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.
Initialization of structs must be guaranteed. This is you do not want the default construction of a struct to throw an exception. For this reason D does not support default constructors in structs. Imagine if
MyStr s;
resulted in an exception being thrown. Instead D provides its own default constructor which initializes all fields to the init property. In your case you are not calling your constructor and just using the provided defaults which means frontArr is never initialized. You want something like:
void main() {
MyStr s = MyStr(10);
s.push(5);
}
It should probably be a compiler error to have default values for all parameters of a struct constructor. Bugzilla
I could be wrong(I haven't used D in a while so it is a bit rusty.) but FrontArr is an array and in your code sample you try to assign a pointer to an array to it. Dynamic arrays work like so(note copied a D tutorial found here)
int[] MyArray;
MyArray.length = 3;
For whatever reason, D doesn't support struct constructors that don't require arguments, either use opCall or remove the default initializer on this()
struct MyStr {
int[] frontArr;
static MyStr opCall() {
MyStr s;
s.frontArr = new int[10];
return s;
}
void push(int x) {
frontArr[0] = x;
}
}
精彩评论