-1

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;
}
Zakir
  • 2,222
  • 21
  • 31
Arka Mukherjee
  • 2,083
  • 1
  • 13
  • 27

4 Answers4

2

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

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
1

What you've just encountered is undefined behaviour, which happens by accessing memory past the end of the array (when you set upper to 7). You are assigning a value to the 8th (index 7, out of bounds element) and then reading the 7th element (index 6, also out of bounds), which happens to just be junk.

Undefined behaviour is just that - undefined. There is no point even figuring out why it happens. It is entirely OS and compiler dependent.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

You have assigned value 66 to 8th element(7th index) of array and you are printing from index number 0 to 6th.So, 6th index is not assigned any value by you. So, it is junk .If you want to add at end then change the line a[upper]=66 to a[upper-1]=66.

-2

Reverse these two lines like this:

a[upper]=66; 
upper=upper+1; 

And your code should be fine.

Akami
  • 1
  • 1
  • That isn't true -- the subsequent `for` loop would still invoke undefined behavior. `upper = upper+1;` has nothing to recommend for it. Also, `a[upper]` itself is out of bounds. – John Coleman Jun 21 '17 at 19:16
  • 1
    This is completely wrong. `a[upper]` is still an attempted out-of-bounds access, since arrays are zero-indexed in C, and the declaration is: `int a[upper];`. – ad absurdum Jun 21 '17 at 19:20