0

Why I am getting wrong output? Suppose, If I am initializing 10 as array initial size and then 15 more elements to append at the end of an array. Then array total size will be 25. But in below code when I input multiple values to append at the end of array then after some input values either program stop or give wrong output.

Help Please !! Is Something wrong with my code?

#include <bits/stdc++.h>
using namespace std;

int main()
{
  int n,elem,lastindex=0;
  cin>>n;
  int arr[n];
  for(int i=0; i<n; i++)
  {
    cout<<"enter index "<<i<<" value number is "<<i+1<<": ";
    cin>>arr[i];
    lastindex++;
  }
  cout<<"lastindex current value: "<<lastindex<<endl;
  cout<<"How many elements you want to add at the end of the element: ";
  cin>>elem;
  elem = lastindex + elem;
  cout<<"elem now: "<<elem<<endl;
  for(int i=lastindex; i<elem; i++)
  {
    cout<<"enter index "<<lastindex<<" value number is "<<lastindex+1<<": ";
    cin>>arr[i];
    arr[lastindex] = arr[i];
    lastindex++;
    cout<<"i: "<<i<<endl;
    cout<<"lastindex: "<<lastindex<<endl;
    cout<<"elem: "<<elem<<endl<<endl;
  }
  cout<<"last index current value: "<<lastindex<<endl;
//  arr[lastindex] = elem;
  for(int i=0; i<lastindex; i++){
    cout<<arr[i]<<" ";
  }
}



  • `int arr[n];` -- This is not valid C++, since `n` is a runtime variable, not a constant. Since it is not valid C++, there is no array in the code you're showing us, only some compiler extension calling itself an array. Instead, use `std::vector arr(n)`, then the functions `push_back`, `insert`, `resize`, etc. are available to you to add values. – PaulMcKenzie Aug 01 '21 at 16:26
  • 1
    What's wrong with it is that it's not valid C++. `bits/stdc++.h` is a non-standard header file. [`using namespace std;` is bad practice](https://stackoverflow.com/questions/1452721/), and you will do yourself a big, big favor if you forget that it exists in C++. And, finally, variable-length arrays are not standard C++ either. Which C++ textbook did you learn all of this -- non-standard header files and variable length arrays -- from? Sounds like a bad textbook, you should find a different one. – Sam Varshavchik Aug 01 '21 at 16:51

1 Answers1

0
cin>>n;
int arr[n];

The size of an array variable must be compile time constant. User input is not compile time constant. This program is ill-formed. Don't do this.

  elem = lastindex + elem;
  cout<<"elem now: "<<elem<<endl;
  for(int i=lastindex; i<elem; i++)
  {
    cout<<"enter index "<<lastindex<<" value number is "<<lastindex+1<<": ";
    cin>>arr[i];
    arr[lastindex] = arr[i];

Here, you access elements outside the bounds of the array. The behaviour of the program is undefined. Don't do this.

I want to add multiple values at the end of the array?

You cannot. The size of an array is constant through its lifetime. There is no way to add elements into an array.

You can use std::vector instead.

eerorika
  • 232,697
  • 12
  • 197
  • 326