Dynamic arrays in C without malloc?

烈酒焚心 提交于 2019-11-29 09:08:53

This is a C99 feature and could be implemented on prior versions by the compiler.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. 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.

Variable-length arrays originated as a GCC extension, but they were also adopted by C99.

They are still being allocated on the stack, so making them "huge" is considered bad style (and will likely break on you someday).

Even before the existence of "variable length arrays," courtesy gcc and C99, there was:

alloca() -- which allows dynamic allocation of stack ("automatic") memory.

"Variable length arrays" were added to the C language in C99. This is covered in §6.7.5.2 "Array declarators":

If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime. Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!