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

时间:2021-08-01 16:19:20

标签: c++ arrays insert

为什么我得到错误的输出? 假设,如果我将 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]<<" ";
  }
}



1 个答案:

答案 0 :(得分:0)

<块引用>
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];

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

<块引用>

我想在数组末尾添加多个值?

你不能。数组的大小在其生命周期中是恒定的。无法将元素添加到数组中。

您可以改用 std::vector