c++ defining array size with a const variable

2019-08-07 11:39发布

问题:

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