-3
#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;
}
4
  • 2
    int LA[] has fixed size, since its initialization. Look up std::vector. Note that LA[j] for j = 5 is already out of range. Commented Feb 3, 2016 at 20:01
  • Please debug your ugly code yourself (or have an const int n = 5;) Commented Feb 3, 2016 at 20:02
  • Possible duplicate of How to resize array in C++? Commented Feb 3, 2016 at 20:02
  • And an even more possible duplicate of "Can you resize a C++ array after initialization?" stackoverflow.com/questions/756906/…. Short answer: you can't. If you need a resizeable array, use std::vector. Commented Feb 3, 2016 at 20:44

2 Answers 2

0

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:

  1. Reserve enough space in your static array to hold everything you need: LA[10] = {...
  2. Use dynamic memory and resize: int *LA = new int[10]; (Look this method up)
  3. The best, use a std::vector<int>.
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.