Reputation:
I apologize in advance if anything isn't clear enough.
While attempting to check if an index value exists of an array in D, I encountered an unexpected RangeError.
I'm attempting to make an array check function, and I wouldn't know how to check for a value in an array in D.
In C, I would use arr[index]
.
Execution Error:
[email protected](6): Range violation
----------------
??:? _d_arrayboundsp [0x100f855d9]
??:? int checkArray(immutable(char)[][]) [0x100f6715e]
??:? _Dmain [0x100f7832e]
Code:
import std.stdio;
import std.stdc.stdlib;
import core.sys.posix.unistd;
int checkArray(string[] arr) {
if (!arr[1]) {
return 0;
} else {
return 1;
}
}
void main() {
string base = "test";
string[] cut = base.split(" ");
checkArray(cut);
}
I currently use a Mac, and used DMD to compile the source.
Should I try some other checker, other than arr[index]
?
Upvotes: 0
Views: 118
Reputation: 40
Firstly, never ever check if an index is within an array by dereferencing it.
bool check(int[] arr, size_t index)
{
return index < arr.length;
}
unittest {
assert(!check([], 0));
assert(!check([1], 1));
assert(check([1, 2], 1));
auto testArray = new int[1024];
//testArray[testArray.length] = 1; // this throws, so check should return false
assert(!check(testArray, testArray.length));
}
enjoy
Upvotes: 1