C
C#•11mo ago
HD-Fr0sT

I am trying to make a list program but i did something wrong

It gives an array index error, can you tell me what i did wrong?
No description
14 Replies
HD-Fr0sT
HD-Fr0sTOP•11mo ago
No description
HD-Fr0sT
HD-Fr0sTOP•11mo ago
the array should be dynamic idk why it does not work
cap5lut
cap5lut•11mo ago
at the very beginning u have int i = list.Length, thats already an invalid index indices start with 0, so the range of valid indices is from 0 to (Length - 1) also note that string[] are arrays not lists, arrays are somewhat similar, but their size does not change actual lists like List<string> are more complex types, which allow adding and removing elements
HD-Fr0sT
HD-Fr0sTOP•11mo ago
so i cant use arrays? or can i use new?
cap5lut
cap5lut•11mo ago
because the very first thing u ask the user is "how many", u still can, u just have to create the array using that number to set the length: string[] list = new string[max];
HD-Fr0sT
HD-Fr0sTOP•11mo ago
oh
cap5lut
cap5lut•11mo ago
between the [ and ] goes the size u want
HD-Fr0sT
HD-Fr0sTOP•11mo ago
btw thanks
cap5lut
cap5lut•11mo ago
glad i could help 🙂
HD-Fr0sT
HD-Fr0sTOP•11mo ago
No description
HD-Fr0sT
HD-Fr0sTOP•11mo ago
@cap5lut what did i do wrong now+ ?
cap5lut
cap5lut•11mo ago
well, max is the length of the array, right? and max - 1 is the last valid index for that array so if i is max + 1, its already 2 more than the last valid index and u do that check after accessing the array, so it errors before u can actually do the check because while loops take already a condition u can basically modify it there
int i = 0;
while (i < list.Length)
{
// do something
i++;
}
int i = 0;
while (i < list.Length)
{
// do something
i++;
}
alternatively u could also write this as for loop:
for (int i = 0; i < list.Length; i++)
{
// do something
}
for (int i = 0; i < list.Length; i++)
{
// do something
}
HD-Fr0sT
HD-Fr0sTOP•11mo ago
thanks again idk what i was thinking
cap5lut
cap5lut•11mo ago
u probably thought of i + 1 == max
Want results from more Discord servers?
Add your server