开发者

Array Size Not Defined? C++

开发者 https://www.devze.com 2023-01-28 01:12 出处:网络
Dumb question. but can you do this. (these are global variables by the way)开发者_运维百科 int size;

Dumb question. but can you do this. (these are global variables by the way)开发者_运维百科

int size;
double Values[size];

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.


No, you can only specify array sizes like this using constant integral expressions. Meaning known at compile-time.

You probably shouldn't be doing this, anyway. Instead, you should be using a vector.

If for whatever reason you can't use a vector (which I would seriously doubt), then your next option would be to use dynamically-allocated arrays. But please, for the love of all that is good int he world, use a smart pointer if you do this.


You can, actually :)

C99 allows that. MSVC doesn't support C99, GCC does.

C++ compilers also tend to allow that as an extension (answer yourself if you're OK with depending on compiler extensions). The only requirement is that you need to know size at the moment of declaration of Values.

A std::vector is usually better (and safer and standarised and so on) anyway, unless you really really want that data on the stack.


You can do it if you allocate them dynamically:

double *Values = new double[size];
...

delete [] Values;

but not statically.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号