在c ++中基于函数参数合法来声明本地数组 [英] Is declaring a local array based on function arguments legal in c++

查看:165
本文介绍了在c ++中基于函数参数合法来声明本地数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一本书,说下面的c ++代码不应该编译:

  void f(int n,int m ){
int a [n],b [n] [m];
}

因为数组的大小在编译时没有确定。 >

但我试过了,发现无论函数是一个全局或成员函数,我可以使用g ++成功编译。



这些东西在最近的c ++实现中是合法的,或者这本书是错误的。



谢谢。



编辑



我立即看到几个回复。我只是有这个奇迹也在Java。我注意到在java,这是支持(请纠正我,如果这也是版本相关)。那么为什么有区别呢?它与使用引用和对象有什么关系吗?但是,在java中,我可以为原语的函数参数声明一个可变长度的数组。



编辑2
$ b

下面的Java代码编译,如果你说不应该:

  class Test1 {
public int [] f(int n,int k){
int [] c = new int [n];
Arrays.fill(c,k);
return c;
}
}


解决方案

称为可变长度数组。它们不允许在C ++中。但是一些编译器(例如GCC)支持它们作为扩展。



在C99中,允许可变长度数组。



编辑:



针对您的新问题。这个问题的最高答案解释了为什么C ++没有可变长度数组。





编辑2:为什么没有可变大小的数组在堆栈?



在Java中,数组是存储在堆而不是调用堆栈中的对象。因此,问题是moot - 所有数组都在堆上,因此VLA不存在。


I read from a book saying that the following c++ code should not compile:

  void f(int n, int m){
     int a[n] , b[n][m];
  }

because the size of the arrays are not determined at compile time.

But I tried it out and found no matter the function is a global one or a member function, I could get compilation successful using g++.

Was this something made legal in recent c++ implementation, or the book is simply wrong.

Thank you.

Edit

I saw a few replies immediately. I just have this wonder too in Java. I notice in java, this is supported (please correct me if this is also version dependent). So why the difference? Does it have anything to do with using references vs. objects? But still, in java, I can declare an array with variable length from function argument for primitives.

Edit 2

The following Java code did compile though, if you say it should not:

class Test1 {
    public int[] f(int n,int k){
        int[] c=new int[n];
        Arrays.fill(c, k);
        return c;
    }
}

解决方案

These are called Variable Length Arrays. They are not allowed in C++. But some compilers (such as GCC) support them as an extension.

In C99, Variable Length Arrays are allowed.

EDIT :

For your new question. The top answer for this question explains why C++ does not have variable length arrays.

Why no variable size array in stack?

EDIT 2:

In Java, arrays are objects which are stored on the heap rather than the call stack. Therefore the question is moot - all arrays are on the heap, hence VLAs don't exist.

这篇关于在c ++中基于函数参数合法来声明本地数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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