为什么从非零索引获取数组有效?

问题描述 投票:0回答:1

据我所知,在 C++ 中,大小为

n
的数组的索引从
0
n-1

但是,这段代码

#include <iostream>
using namespace std;

int main() {
  int n;
  cin >> n;
  int a[n];
  int os = 2;
  for(int i = os; i < n+os; i++) {
    cin >> a[i];
  }
  for(int i = os; i < n+os; i++) {
    cout << a[i] << " ";
  }
  cout << endl;

  return 0;

}
即使我使用从

2

n+1
 的索引,
也会给出预期的输出。

这对于

os
的某些小值给出了预期输出,但在大值时给出了运行时错误。我预计除了
os
之外的任何
0
值都会失败。

知道它为什么起作用以及内存到底发生了什么吗?

c++ arrays indexing runtime-error
1个回答
0
投票
try this : 
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    int os = 2;
    for(int i = os; i < n+os; i++) {
        cin >> a[i];
    }
    for(int i = os; i < n+os; i++) {
        cout << a[i] << " ";
    }
    cout << endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.