在C ++中在不同长度的堆栈上的数组分配 [英] Array allocation in C++ on stack with varying length

查看:114
本文介绍了在C ++中在不同长度的堆栈上的数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我惊讶地发现,可以在C ++中在堆栈上分配一个变长数组(例如 int array [i]; )。它似乎工作正常对clang和gcc(在OS / X),但MSVC 2012不允许它。

I was surprised to find out that it is possible to allocate an varying-length array on the stack in C++ (such as int array[i];). It seems to work fine on both clang and gcc (on OS/X) but MSVC 2012 don't allow it.

这种语言功能叫什么?它是一个官方的C ++语言功能吗?如果是,C ++的哪个版本?

What is this language feature called? And is it an official C++ language feature? If yes, which version of C++?

完整示例:

#include <iostream>

using namespace std;

int sum(int *array, int length){
    int s = 0;
    for (int i=0;i<length;i++){
        s+= array[i];
    }
    return s;
}

int func(int i){
    int array[i]; // <-- This is the feature that I'm talking about
    for (int j=0;j<i;j++){
        array[j] = j;
    }

    return sum(array, i);

}

int main(int argc, const char * argv[])
{
    cout << "Func 1 "<<func(1)<<endl;
    cout << "Func 2 "<<func(2)<<endl;
    cout << "Func 3 "<<func(3)<<endl;

    return 0;
}


推荐答案

可变长度数组。这是一个GNU扩展,不是标准的C ++。

You're looking at GCC's variable length arrays. That's a GNU extension and is not standard C++.

这篇关于在C ++中在不同长度的堆栈上的数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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