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


i have program defines const int value size of arrays. there anyway can change value of var when program first ran? need set once @ start cannot program compile when trying set using cin i'm getting error stating that:

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

which understand mean there no value set array size cannot compile. have tried initializing var want set 1 , change once program being ran i'm having no luck either, getting same error.

edit: first 2 lines new var , new const int i'm looking change , below lines errors seems originating from.

int objectindexsize; const int numofobjects = objectindexsize; mat imagearray[numofobjects]; mat descriptorsarray[numofobjects]; vector<keypoint> keypointarray[numofobjects]; string objectname[numofobjects]; string filenamepostcut[numofobjects]; 

variables such as

int arr[10]; 

are embedded in executable under .data section. have 40 bytes of zeros. these 40 bytes there when load executable image (.code, .data , others) ram. there won't need allocate anything, since done os.

(not sure if case big chunks of memory, since memory can fragmented, , executable image shouldn't. perhaps compiler magic behind scenes.)

anyway, reason why can't do

int n = 10; int arr[n]; 

but can do

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

is because in first case compiler doesn't know n constant (it might figure out optimization, idea), , in second case never change, meaning compiler knows how memory pre-allocate in executable you.

now, can't const int a; std::cin >> a; because that's not constant @ all.

what can 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 , tell reserve memory you're going need this:

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

if know size won't change, might want use pointers instead of vectors.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -