为什么这样的程序可以静态分配内存?


   
  int main(int argn, char** argv)
  
{
int a;
scanf("%d",&a);
int b[a];

printf("size of array = %d\n", sizeof(b));

return 1;
}

为什么b[a]能根据输入来分配内存?难道这是新的编程规范或者标准吗?

c 数据结构

早睡早起身体好 12 years, 8 months ago

Variable Length Arrays are not approved by C++ standard. C++ Standard mandates that the size of an array must be an compile time constant.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C89 mode and in C++. (However, GCC’s implementation of variable-length arrays does not yet conform in detail to the ISO C99 standard.) These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited.
另外,VLA 需要支持 sizeof 运算, 动态sizeof 也是C99的一个特有特性。
目前很多C++编译器尚不能支持动态数组特性(VC++2005不支持此特性, GCC3.2之后支持)
关于VLA,需要注意一下几点:
1. VLA的空间是函数栈中是一个automatic,在声明处分配,在作用域结束处释放。
2. VLA不能位于在静态存储区(包括全局变量和静态变量)中,也就是说不能添加static修饰或在任何函数体外定义

参考链接:
C语言变长数组之剖析
GCC变长数组VLA (allowed in ISO C99)

三倍速草泥马 answered 12 years, 8 months ago

Your Answer