数组大小未定义? C++
愚蠢的问题。但你能做到吗? (顺便说一下,这些是全局变量)
int size;
double Values[size];
如果我从文件中获取大小?
我知道你可能不能,但也许他们有一些方法可以根据我从文件中读入的数字重新调整大小(比如我读入 7,我知道值的大小必须为 7)。
编译器抱怨,但我想知道它们是否是一些解决方法。 (顺便说一句,这些必须保留为全局变量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以,您只能使用常量积分表达式来指定数组大小。含义在编译时已知。
无论如何,你可能不应该这样做。相反,您应该使用向量。
如果出于某种原因您无法使用向量(我对此表示严重怀疑),那么您的下一个选择将是使用动态分配的数组。但是,为了世界上一切美好的事物,如果您这样做,请使用智能指针。
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.
你可以,实际上:)
C99 允许这样做。 MSVC 不支持 C99,GCC 支持。
C++ 编译器也倾向于允许作为扩展(如果您同意依赖编译器扩展,请自行回答)。唯一的要求是您需要在声明
Values
时知道size
。无论如何,
std::vector
通常更好(并且更安全和标准化等等),除非您真的真的希望该数据位于堆栈上。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 ofValues
.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:
but not statically.