#include <iostream>
using namespace std;
/* This code is not working as it does not insert the value of item in the
array instead the value of item is zero. But i have troubleshooted this
problem and figured out that the code works fine if i define "int item" as
constant variable or use int i as global variable instead of defining in the
for loop. so my question is what is the reason behind this malfunctioning or
is there any programming secret i haven't aware of yet*/
int main()
{
int LA[] = {1, 3, 64, 98, 54};
int k = 3;
int n = 5;
int item = 46;
int j = n;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
n++;
for( ; j >= k; j-- )
{
LA[j+1] = LA[j];
}
LA[k] = item;
cout << endl << "After insertion" << endl << endl;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
return 0;
}
2 Answers
LA has a fixed size. It is a static array, and you cannot change the size in c or c++. Currently j will be 5 and you will attempt to access LA[5] which is outside the bounds of the array and Undefined Behaviour.
You have 3 options:
- Reserve enough space in your static array to hold everything you need:
LA[10] = {... - Use dynamic memory and resize:
int *LA = new int[10];(Look this method up) - The best, use a
std::vector<int>.
Comments
If you wanna insert item as k'th element of array, You should know that the LA array has not 6th index (LA[6]). So before the second loop, initialize j with n-1.
Also if you wanna have all the values, You should use std::vector which can add the values and indexes, dynamically.
For further studies about vectors see this link: Here
int LA[]has fixed size, since its initialization. Look upstd::vector. Note thatLA[j]forj = 5is already out of range.const int n = 5;)