to anyone who can help. I am a beginner in the D language. I am facing an index violation issue that I am unable to resolve. The logic of the program seems to be correct, as something similar in C and C++ works (I have already tested it).
Here is the code:
import std.stdio;
void main()
{
float[8][4] NOTAS;
int I, J;
writeln("2D ARRAY - INPUT AND OUTPUT\n");
for (I = 0; I < 8; I++)
{
writefln("Enter grades for student %d:", I + 1);
for (J = 0; J < 4; J++)
{
writef("Grade ==> %d: ", J + 1);
readf(" %f", &NOTAS[I][J]);
}
writeln();
}
writeln("\nGRADE REPORT\n");
writeln("Student Grade1 Grade2 Grade3 Grade4");
writeln("------- ------ ------ ------ ------");
for (I = 0; I < 8; I++)
{
writef("%7d", I + 1);
for (J = 0; J < 4; J++)
{
writef("%7.1f", NOTAS[I][J]);
}
writeln();
}
}
Here are the steps of the program's operation and the error message encountered:
2D ARRAY - INPUT AND OUTPUT
Enter grades for student 1:
Grade ==> 1: 1
Grade ==> 2: 1
Grade ==> 3: 1
Grade ==> 4: 1
Enter grades for student 2:
Grade ==> 1: 2
Grade ==> 2: 2
Grade ==> 3: 2
Grade ==> 4: 2
Enter grades for student 3:
Grade ==> 1: 3
Grade ==> 2: 3
Grade ==> 3: 3
Grade ==> 4: 3
Enter grades for student 4:
Grade ==> 1: 4
Grade ==> 2: 4
Grade ==> 3: 4
Grade ==> 4: 4
Enter grades for student 5:
core.exception.RangeError@main.d(16): Range violation
----------------
??:? onRangeError [0x45cbb9]
/home/runner/TreasuredThoughtfulAssembler/main.d:16 _Dmain [0x4150dd]
Grade ==> 1: exit status 1
Has anyone experienced this before and can share their insights? Thank you in advance.
Note: I am running tests on Replit.
I have already tried changing the loop flow from "I = 0; I < 8; I++" to "I = 0; I <= 7; I++". I have also tried changing the dimension of the variable NOTAS from "[8][4]" to "[9][5]", but nothing has had any effect. The impression I got is that the variable "I" progresses from 0 to 4, and when it reaches 5, it violates the index of NOTAS.
C does arrays of arrays in a bizarre way, where use mirrors declaration. D always does it in a consistent order: int[5] x;
is a 5-length array of ints, and int[5][4]
is a 4-length array of 5-length arrays of ints.
As such, the use in C is reversed compared to the use in D.
C: int a[5][4]; max index: a[4][3]; D: int[5][4]; max index: a[3][4];