简体   繁体   中英

c++ defining array size with a const variable

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?

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

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

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 = {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM