Write a program that defines an array of type integer Print
Solution
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[5]={1,2,3,4,5};
int i;
for( i=0;i<5;i++)
{
cout<<a[i]<<\" at \"<<i+1<<endl;
}
a[i++]=5;
a[i]=6;
for( i=0;i<6;i++)
{
cout<<a[i]<<\" at \"<<i+1<<endl;
}
return 0;
}
===================================
1 at 1
2 at 2
3 at 3
4 at 4
5 at 5
1 at 1
2 at 2
3 at 3
4 at 4
5 at 5
5 at 6
================================
Above code will work because we have initilise at compile time
But if we accept at run time it will show garbage values
#include<stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int i;
for( i=0;i<5;i++)
{
printf(\"%d\ \",a[i]);
}
i++;
scanf(\"Enter next ele%d\ \",&a[i]);
i++;
scanf(\"Enter next ele%d\ \",&a[i]);
for( i=0;i<7;i++)
{
printf(\"%d\ \",a[i]);
}
return 0;
}
===============================
1
2
3
4
5
6
1
2
3
4
5
32767
0
As we can see last 2 values are not valid
Conclusion:
Arrays in C are allocated contiguous memory. If initially memory is allocated for 8 elements and you store 10 elements, the last two elements are stored in memory contiguous with the memory allocated for the array. What happens as a result depends on the situation. If the additional two elements stored happen to be in an area of memory already allocated to a different object, the value of that object gets corrupted. If that memory location is unallocated you could use the array without any side effects as long as that memory remains unallocated. If subsequently that memory is allocated to another object and that object is initialized, the last two element values get corrupted.
You can Declare an Array of size m but store n elements , where m<n , but the elements stored after the mth location will not be considered to be within the Declared array. still you can access beyond the array limit.Actually it is one the disadvantages of C where it does not do array bound checking and allows to store more than specified elements
============================================
Comment about work
================================

