C ++ int a [n]可在g ++中使用,但不能与vs2008一起使用 [英] C++ int a[n] working in g++ but not with vs2008

查看:96
本文介绍了C ++ int a [n]可在g ++中使用,但不能与vs2008一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

...
int n;
cin >> n;
int numbers[n];
...

它在Mac上使用g ++在NetBeans上进行了编译(我认为),而在Windows上却没有使用VS2008进行编译.为什么让每个编译器都可以使用它如此困难?分配数组之前先知道数组的大小.

It compiled with NetBeans on Mac using g++ (I think) and it didn't compile using VS2008 on Windows. Why is it so hard to make it work with every compiler? The size of the array is known before allocating it.

我了解 std :: vector .实际上,这是家庭作业的一部分,我在Mac上开始工作,然后回到家,感到惊讶,因为它在VS2008上不起作用.感谢所有的答案.但是我仍然觉得合乎逻辑,如果编译器可以生成诸如 alloc(123)之类的代码,其中值123是硬编码的,为什么它不能生成诸如 alloc(n)之类的东西?code>,您从包含 int n 或其他内容的内存地址中获取 n .默认情况下允许这样的事情似乎更合逻辑.

I know about std::vector. Actually this was part of a homework assignment and I started it at work on a mac, then got home and was surprised that it didn't work on VS2008. Thanks for all the answers. But I still find it logical that if the compiler can generate some code like alloc(123) where the value 123 is hardcoded, why can't it generate something like alloc(n) where you get n from a memory address that holds an int n or something. It just seems more logical to allow something like this by default.

推荐答案

尽管数组的大小在分配之前是已知的,但直到运行时才知道.这称为可变长度数组(VLA),是一种C99ism,在g ++中由默认启用的扩展支持.明确地说,这不符合C ++ 98/03,因此Visual C ++有权拒绝它.

Although the size of the array is known before it is allocated, it's still not known until runtime. This is known as variable length array (VLA) and is a C99ism, supported in g++ by an extension that is enabled by default. To be explicit, this is not conformant C++ 98/03, and thus Visual C++ is well within its right to reject it.

如果您真的想要运行时动态调整大小,请在堆上分配(通过new []).这将在任何地方都可以使用,并且作为一项奖励,可以防止堆栈溢出.

If you really want runtime dynamic sizing, allocate on the heap (via new[]). That will work everywhere, and as a bonus, protect you from stack overflows.

这篇关于C ++ int a [n]可在g ++中使用,但不能与vs2008一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆