数组大小(以C++为单位)

Array size in C++

本文关键字:C++ 为单位 数组      更新时间:2023-10-16

我制作了一个代码,其中我必须将数组的大小作为用户的输入及其元素并打印它们。

#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
int main()
{
int i;
cout<<"nenter the size of array";
cin>>i;
int n[i];
for(int j=0;j<=i;j++)
{
cout<<"nn["<<j<<"]=";
cin>>n[j];
}
for(int k=0;k<=i;k++)
{
cout<<endl;
cout<<"nn["<<k<<"]=";
cout<<n[k];
}
}

假设如下:i的值为 3(根据用户的输入)。 在第一个循环中,j的条件是<=i其中 i 是数组的大小(这不应该发生,因为i从 0 开始),因此编译器要求我为数组输入 4 个值(n[0]n[1]n[2]n[3]),但数组的大小仅为 3。它如何存储 4 个对象?

更改以下内容:

for(int j=0;j<=i;j++)

对此:

for(int j = 0; j < i ; j++)

由于数组索引以数组大小减 1 结束。在您的情况下i - 1.

同样,你for(int k=0;k<i;k++).

您发布的代码通过越界访问数组来调用未定义的行为


这:

int n[i];

是一个可变长度数组 (VLA),它不是标准C++,但受某些扩展支持。

如果你用pedantic标志编译,你会得到:

prog.cc: In function 'int main()':
prog.cc:9:9: warning: ISO C++ forbids variable length array 'n' [-Wvla]
int n[i];
^

如果你想要类似这种数据结构的东西,那么我建议你改用std::vector,这是标准C++。


顺便说一句,这不是语法错误或其他什么,但i通常用作计数器(就像您使用j一样),如果您愿意,可以将其用作i ndex。因此,我会将其名称更改为大小,例如,或相关名称。


编辑:

std::vector和变量重命名的示例:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
int tmp, n;
cout<<"Input number of elementsn";
cin >> n;
vector<int> v;
for(int i = 0; i < n; ++i)
{
cin >> tmp;
v.push_back(tmp);
}
for(auto number: v)
cout << number << endl;
return 0;
}

您需要检查小于 i 且不小于等于 i。 否则,它将尝试存储 0,1,2,3 的值,在这种情况下,最后一个对象将导致内存损坏。在 c++ 中,即使您尝试在大小为 3 的数组中添加 100 个成员,它也不会给您任何错误。

在开始编码之前,最好先阅读 c++ 中的内存管理。