数组大小未定义? C++

发布于 2024-10-04 16:05:51 字数 237 浏览 1 评论 0原文

愚蠢的问题。但你能做到吗? (顺便说一下,这些是全局变量)

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只涨不跌 2024-10-11 16:05:51

不可以,您只能使用常量积分表达式来指定数组大小。含义在编译时已知。

无论如何,你可能不应该这样做。相反,您应该使用向量。

如果出于某种原因您无法使用向量(我对此表示严重怀疑),那么您的下一个选择将是使用动态分配的数组。但是,为了世界上一切美好的事物,如果您这样做,请使用智能指针。

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.

尛丟丟 2024-10-11 16:05:51

你可以,实际上:)

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 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.

抹茶夏天i‖ 2024-10-11 16:05:51

如果动态分配它们就可以做到:

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

delete [] Values;

但不能静态分配。

You can do it if you allocate them dynamically:

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

delete [] Values;

but not statically.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文