dyanamic allocation on stack on run time
main()
{
int i=256;
char buf[i];
}
perfectly compile on g++ but gives an error on visual studio 8.
anybody know why 开发者_JAVA技巧it is happening,
Thanks
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++
(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.
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.
If you need a dynamic array in C++, use std::vector
.
Note in C++ you need to specify a return type for main
. This is and always shall be int
.
As said before, what you are doing isn't part of the C++ standard. However, you can create a variable-length array on the stack in C++ with:
{
int length=256;
char *buf = _alloca(length * sizeof(char)); // allocates space on the stack
// that is freed when function returns
}
alloca()
is not part of the standard either, but both gcc and Visual Studio support it. Be aware: the space it allocates is freed when you exit the function, not at the end of buf
's scope! alloca()
inside a loop will lead to suffering.
If you do not absolutely positively need your array to be on the stack instead of on the heap, then use a standard container like std::vector
instead; it is on the heap, but knows how to clean up after itself.
Variable length arrays are allowed in C99, but not in Visual C++. VC++ is not based on C99.
Several additions of C99 are not supported in C++ or conflict with C++ features.
Source
With Visual C++ you can use a variable as the array size for the stack. But it must be a constant expression and determinable at compile time.
You can of course create a dynamically sized array at runtime by using the heap:
char *buf = new char[i];
//do something
delete[] buf;
But most of the time you would want to use an appropriate STL container such as std::vector
.
In this case you can just use const:
int main()
{
const int i=256;
char buf[i];
}
Also note, that main
without int
as its return type is not valid C++.
精彩评论