由于大小可变,未创建数组

array not being created due to variable size

本文关键字:创建 数组 于大小      更新时间:2023-10-16

我收到与数组大小相关的错误,错误是:

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];