数组大小(以C++为单位)
Array size in C++
我制作了一个代码,其中我必须将数组的大小作为用户的输入及其元素并打印它们。
#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++ 中的内存管理。
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 正向声明的枚举,默认值以.h为单位
- 常量"C"占用的空间(以字节为单位)