Colin747
Colin747

Reputation: 5013

Read in value of const int when ran - C++

I have a program which defines a const int as a value for the size of arrays. Is there anyway I can change the value of this var when the program is first ran? I only need it to be set once at the start but I cannot get the program to compile when trying to set it using cin as I'm getting an error stating that:

error: array bound is not an integer constant before ‘]’ token

Which I understand to mean that there is no value set for the array size so it cannot compile. I have also tried initializing the var I want to set to 1 and then change it once the program is being ran but I'm having no luck with that either, getting the same error.

EDIT: The first two lines are the new var and new const int I'm looking to change and below are the lines that the errors seems to be originating from.

int objectIndexSize;
const int numOfObjects = objectIndexSize;
Mat imageArray[numOfObjects];
Mat descriptorsArray[numOfObjects];
vector<KeyPoint> keypointArray[numOfObjects];
String objectName[numOfObjects];
String fileNamePostCut[numOfObjects];

Upvotes: 0

Views: 347

Answers (2)

rr-
rr-

Reputation: 14831

Variables such as

int arr[10];

are embedded in your executable under .data section. You have 40 bytes of zeros. These 40 bytes will be there when you load your executable image (.code, .data and others) into RAM. There won't be any need to allocate anything, since it was already done by the OS.

(Not sure about if that is the case with very big chunks of memory, since memory can be fragmented, and executable image shouldn't. Perhaps compiler does some magic behind the scenes.)

Anyway, this is the reason why you can't do

int n = 10;
int arr[n];

but you can do

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

is because in the first case compiler doesn't know n is constant (it might figure it out thanks to optimization, but you get the idea), and in the second case it will never change, meaning the compiler knows how much memory to pre-allocate in the executable for you.

Now, you obviously can't do const int a; std::cin >> a; because that's not a constant at all.

What you can do is to use either:

int n;
std::cin >> n;
std::unique_ptr<int[]> arr(new int[n]); //C++11
//or
int *arr = new int[n]; //before C++11

or use vector and tell it to reserve the memory you're going to need like this:

int n;
std::cin >> n;
std::vector<int> arr;
arr.reserve(n);

If you know the size won't change, you might want to use the pointers instead of vectors.

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65630

You can't allocate arrays on the stack dynamically. You should instead use std::vector.

Upvotes: 2

Related Questions