I tried to insert an element in an array and it failed with array index out of bounds
I tried in C# it failed it works fine in c
int[] LA = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k)
{
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
but it works in c
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
printf("j+1 =%d",j+1);
LA[j+1] = LA[j];
j = j - 1;
}
Can someone please explain why this is? and what about other languages will it keep varying? Thanks.
Many answers say it doesn't work in c so i have uploaded an image
]1
LA[6], so using aList<T>won't help.int* LA = stackalloc int[] { 1, 3, 5, 7, 8 };- done! this will also "work" for the same reasons (meaning: it is equally broken) - the reasons here being: your C array isn't bound-checked (just like my C# pointer); you have then accessed memory past the end of the defined range - that might be unused memory, it could be something really important, it could be an invalid page; at that point: your code is just broken