首页 > 解决方案 > 参数不能用作常数

问题描述

我刚刚完成了我的代码,我被最后两个错误困住了:“参数“n”的值不能用作常数。” 我在我的函数中使用“int n”来计算平均时间。

void findavgTime(int option, int pids[], int arrivals[], int n, int bursts[], int quanta) { 

int resp[n], ta_time[n], avg_resp_time = 0, avg_ta_time = 0; 

我该怎么办?

标签: c++arrays

解决方案


在 C++ 中,数组的大小必须是编译时常数。所以你不能写这样的代码:

int n = 10;
int arr[n];    //incorrect

正确的写法是:

const int n = 10;
int arr[n];    //correct

出于同样的原因,您的代码中的以下代码也是不正确的:

int resp[n], ta_time[n];//incorrect because n must be a compile time constant

您可以将std::vector<>其用于您的目的,而不是使用内置数组。std::vector因此,您可以拥有/创建命名的数组,而不是创建数组respta_time如下所示:

//n denotes the size. You can also use std::vector::reserve for requesting that the vector capacity be at least enough to contain n elements
std::vector<int> resp(n); 
std::vector<int> ta_time(n);

推荐阅读