declaring array using non-const variable to id size

J

Jim Hudon

i need to create an array of a size determined by a non-const variable:

int char sampleArray[ arraySize ];

why does the following not work, and what can i do:

const int constArraySize = arraySize;
int char sampleArray[ constArraySize;

for both of the above, i get the same error message when i compile:

"storage size of 'sampleArray' is not constant"

thanks...
 
S

Siemel Naran

i need to create an array of a size determined by a non-const variable:

int char sampleArray[ arraySize ];

why does the following not work, and what can i do:

const int constArraySize = arraySize;
int char sampleArray[ constArraySize;

for both of the above, i get the same error message when i compile:

"storage size of 'sampleArray' is not constant"

At present, the size of an array must be a compile time constant. So you
can say

const int constArraySize = 10;
int char sampleArray[ constArraySize ];

What is "int char"?

You can use std::vector though.

std::vector<int> sampleArray(constArraySize);
 
K

Kai-Uwe Bux

Jim said:
i need to create an array of a size determined by a non-const variable:

int char sampleArray[ arraySize ];

why does the following not work, and what can i do:

const int constArraySize = arraySize;
int char sampleArray[ constArraySize;

for both of the above, i get the same error message when i compile:

"storage size of 'sampleArray' is not constant"

thanks...


C++ requires that the size of a statically allocated array be known at
compile time.

Your options are:

a) use a dynamically allocated array:

char* sampleArray ( new char [ arraySize ] );

The drawback is that you have to take of memory management yourself.
Therefore, it is probably better to:

b) use std::vector.

#include <vector>
...
std::vector< char > sampleArray ( arraySize );

This will allocate a vector of length arraySize. You can use it almsost as
you would use an array. Upon destruction, memory will be released to the
system automatically.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top