printf("Enter position : ");
scanf("%d", &pos);
printf("Enter element : ");
scanf("%d", &element);
for ( i = 4; i >= (pos-1); i--)
{
a[i+1]=a[i]; // why is this loop only working one time when pos=3
}
this is the portion of my code where i am trying to insert an element into an array of size 5 with 4 elements by starting to shift elements to the next indexes but i am shifting from the fifth element itself that is 0(or garbage value) . i know this is not the correct way to achieve insertion but my question is why this line of code is not working
a[i+1]=a[i];
also the loop doesn't seem to work 3 times but instead 1 time .( which is my main question )
my original code :
#include<stdio.h>
int main(){
int a[5],i, pos , element;
printf("Enter elements : ");
for ( i = 0; i < 4; i++)
{
scanf("%d",&a[i]);
}
printf("Enter position : ");
scanf("%d", &pos);
printf("Enter element : ");
scanf("%d", &element);
for ( i = 4; i >= (pos-1); i--)
{
a[i+1]=a[i];
}
a[pos-1]=element;
for ( i = 0; i < 5; i++)
{
printf("%d ",a[i]);
}
return 0;
}
This for loop
is accessing memory outside the array when
iis equal to4due to the expressiona[i+1]that in this case is equivalent toa[5]while the valid range of indices is[0, 4].So the code invokes undefined behavior.
Also if you want to add a new value at the position
posthen using this condition in the for loopinstead of at least this condition
does not make sense.
And you should check that the value of the variable
posis in the range of valid indices. For example as the variableposhas the signed integer typeintthen nothing prevents the user to enter a negative value.Instead of writing the for loop that is error prone you could use standard C string function
memmovedeclared in the header<string.h>.For example
As for the for loop then it can look for example the following way
Also pay attention to that the first for loop
leaves the last element of the array uninitialized.
Try to not use magic numbers like 4 or 5. Use named constants as for example