C ++防爆pression必须具有恒定值 [英] C++ Expression must have constant value

查看:191
本文介绍了C ++防爆pression必须具有恒定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iomanip>
#include <iostream>
#include <Windows.h>
using namespace std;



template <class T>
void sort(int n, T a[]){
       for(i=0;i<n-1;i++){
          for(j=i;j<n;j++){
               if(a[i] > a[j]){
               temp=a[i];
               a[i]=a[j];
               a[j]=temp;
               }
           }
     }
}


void main(){
    int size;
    cout<<" Please input the amount of numbers you would like to sort"<<endl;
    cin>>size;
    int Amta[size];
    for(int i=0; i<size; i++){
        cout<<"Please enter the "<<size+1<< "number";
        cin>>Amta[i];
    }
    Sleep(100000);


}

我想获得多少个号码的用户想从用户输入,并将其存储在变量的大小;但是当我数组初始化AMTA【尺寸】我得到前pression必须有固定值和C2057:预期不断前pression编译错误

i am trying to get the how many numbers the user would like to input from the user and store it in the variable size; but when i initialize array Amta[size] i get "Expression must have constant value" and "C2057: expected constant expression" compile error.

推荐答案

您不能在声明阵列输入括号之间的非恒定值:

You can't enter a non-constant value between the brackets when you declare your array:

int Amta[size];

既然你得到尺寸从用户,编译器不能提前告诉它需要多少内存为 AMTA 。在这里(尤其是练习)最简单的办法是只选择一个相对较大的值,并做出不断的分配,如:

Since you're getting size from the user, the compiler can't tell ahead of time how much memory it needs for Amta. The easiest thing to do here (especially for an exercise) is to just choose a relatively large value and make that the constant allocation, like:

int Amta[1024];

,然后如果你要小心(你应该),您可以检查如果(大小&GT; 1024),如果用户想要的尺寸的打印错误超过pre-分配的边界。

And then if you want to be careful (and you should) you can check if (size > 1024) and print an error if the user wants a size that's beyond the pre-allocated bounds.

如果你想获得幻想,你可以定义 AMTA 没有pre-集的大小,就像为int * AMTA; 然后与后来分配它的malloc

If you want to get fancy, you can define Amta with no pre-set size, like int *Amta; and then you allocate it later with malloc:

Amta = (int *)malloc(sizeof(int) * size);

则还必须免费 AMTA 之后,当你用它做:

free(Amta);

这篇关于C ++防爆pression必须具有恒定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆