在运行时堆栈上的动态分配 [英] dyanamic allocation on stack on run time

查看:268
本文介绍了在运行时堆栈上的动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main()
{
int i=256;
char buf[i];
}

在g ++上完美编译,但在visual studio 8上出现错误。

perfectly compile on g++ but gives an error on visual studio 8.

任何人都知道为什么会发生,

anybody know why it is happening,

感谢

推荐答案

在C ++中,数组有一个常量大小。然而,在C99中,存在称为可变长度数组或VLA的东西。这是你在这里做的。

In C++, arrays have a constant size. In C99, however, there exist something called variable-length arrays, or VLA's. This is what you're making here.

g ++ (C ++编译器)是 gcc (C编译器)和 g ++ 允许你使用C99特性,而VS没有这样的事情。基本上它是一个非标准的C ++扩展。

g++ (the C++ compiler) is a sibling of gcc (the C compiler), and g++ is allowing you to use that C99 feature, while VS has no such thing. Essentially it's a non-standard C++ extension.

如果你使 i (因为是标准C ++):

If you make i a compile-time constant, it would work (since that's standard C++):

const int i = 256; // obviously cannot change at runtime.

如果您需要C ++中的动态数组,请使用 std :: vector

If you need a dynamic array in C++, use std::vector.

注意,在C ++中,您需要为 main 指定返回类型。这总是 int

Note in C++ you need to specify a return type for main. This is and always shall be int.

这篇关于在运行时堆栈上的动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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