由于大小可变,未创建数组
array not being created due to variable size
我收到与数组大小相关的错误,错误是:
line 19: expression did not evaluate to a constant <br/>
line 31: array type 'int[*n]' is not assignable <br/>
line 34: array type 'int[*n]' is not assignable <br/>
#include "stdafx.h"
#include "iostream"
int main()
{
using namespace std;
int x=0;
int cst=0;
int cstF=0;
int rst=0;
int n=1;
cout << "insira o numero de consultas" << endl;
cin >> n;
int hora[2 * n];
for (x = 0; x == 2 * n - 2; x += 2)
{
cout << "insira o horario de inicio" << endl;
cin >> cst;
if (hora[x - 2] < cst && hora[x - 1] > cst)
rst = rst;
else
{
rst = rst + 1;
}
hora[x] = cst;
cout << "insira o horario de termino" << endl;
cin >> cstF;
hora[x + 1] = cstF;
}
cout << "o numero de consultas possiveis eh: " << rst << endl;
return 0;
}
我真的很感激为什么我遇到错误。
您不能使用变量作为大小静态分配数组;
int n;
int hora[n]; //won't compile
您可以使用动态内存分配:
int n;
int* hora = malloc(sizeof(int)*n);
使用常量变量:
const int n = 10;
int hora[n];
如果您坚持在运行时从控制台(或其他任何地方)读取大小,并静态分配内存,则可以执行以下操作:
int n;
cin >> n;
const int size = n;
int hora[size];
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?