# Thread: Need explanation on coding.

1. ## Need explanation on coding.

Code:
```         printf("\nEnter location of deletion: ");
scanf("%d", &loc);

item = a[loc-1];
for(i=loc-1; i<n; i++)
{
a[i] = a[i+1];
}
n--;
printf("\nITEM deleted: %d", item);```
what does a[loc-1] and a[i+1] mean? I still don't get it

2. If you have array of 5 elements for example. First element's index is zero, second element's index is one, third's two and so on. Basically array[n] goes from 0 to n-1. If you want to delete third element you actually need to delete element 3-1. But your program don't erase element, it just overwrites it.

3. so that mean -1 is somewhat of delete right? if i want delete second element will be 2-1? how about i+1?

4. Originally Posted by Alexie
so that mean -1 is somewhat of delete right? if i want delete second element will be 2-1? how about i+1?
Try reading this: Arrays in C - Cprogramming.com

5. Code:
```printf("\nEnter location of deletion: ");
scanf("%d", &loc);

item = a[loc-1];
for(i=loc-1; i<n; i++)
{
a[i] = a[i+1];
}
n--;```
Assuming n is the total number of elements in the array, this code has a buffer overflow.

The deletion works by storing the value to delete in item and then shifting each element after the one which gets deleted one place to the left (a[i] = a[i + 1]). Thus reducing the number of elements in the array by 1 (n--).
This also means that the for loop should only increment i up to n - 2. In your example i becomes n - 1 which means that i + 1 is n and a[n] is out of bounds.

Bye, Andreas

Popular pages Recent additions