我想在数组末尾添加多个值?我用下面的代码没有得到正确的答案?

I want to add multiple values at the end of the array? I am not getting right answer with below code?

为什么我得到错误的输出? 假设,如果我将 10 初始化为数组初始大小,然后再将 15 个元素附加到数组末尾。然后数组总大小将为 25。但是在下面的代码中,当我输入多个值以附加在数组末尾时,然后在一些输入值之后程序停止或给出错误的输出。

求助!!我的代码有问题吗?

#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]<<" ";
  }
}



cin>>n;
int arr[n];

数组变量的大小必须是编译时常量。用户输入不是编译时常量。该程序格式错误。不要这样做。

  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];

在这里,您访问数组边界之外的元素。程序的行为是未定义的。不要这样做。

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

你不能。数组的大小在其整个生命周期内保持不变。无法将元素添加到数组中。

您可以改用 std::vector