I am trying to insert an integer at the end of an array. However, a random value(47) shows up at the last position when I am trying to execute the code. 47 doesn't change even if I change the value to be inserted. Output is this.
Can anyone tell me why it is 47? And is it a garbage value? My code is as follows:-
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int upper=6;
int a[upper];
int i;
for(i=0;i<upper;i++)
{
scanf("%d",&a[i]);
}
printf("The array before insertion is \n");
for(i=0;i<upper;i++)
{
printf("%d \n",a[i]);
}
printf("\n The array after insertion is \n");
upper=upper+1;
a[upper]=66;
for(i=0;i<upper;i++)
{
printf("%d \n",a[i]);
}
return 0;
}
you declare an array with size upper
(6) but here:
a[upper]=66;
you try to access the 8th location of the array (since you did before that upper= upper + 1
)- a location you don't own. What you are doing is UB and therefore it can print 47 or anything else can happen