c++ defining array size with a const variable

。_饼干妹妹 提交于 2019-12-11 08:27:32

问题


int place = determinePlace(input);

const int arraySize = (place + 1);
int decimal[arraySize] = {};

Hi!

I tried to use a const int variable to define the array size of decimal[]. However, error C2057 and error C2466 keeps on coming up.

Are there any suggestions?


回答1:


Joachim is right, you are trying to set:

const int arraySize = (determinePlace(input) + 1);

this doesn't work, because you are trying to get a user input or something similar which will be only accessible when you run the program not when you compile it.

I would try something like this:

#include <vector>

using std::vector;

vector<int> decimal;
decimal.resize(determinePlace(input) +1);
decimal = {};



回答2:


Even if you declare arraySize as const, it's still not a compile-time constant since it have to be calculated run-time.

Use std::vector instead:

std::vector<int> decimal(arraySize);



回答3:


array size should be int , unsigned, unsigned int or size_t not a decimal type double

use std::vector

to use

#include <vector> // include the header 

to define a vector

std::vector<int> vec = {1, 2, 3, 4, 5};

this defines vector int with a values of 1, 2, 3, 4, 5

to add some values

vec.push_back(12);

adds 12 to vec vector



来源:https://stackoverflow.com/questions/31090633/c-defining-array-size-with-a-const-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!