Dynamic array in Stack?
Is this correct ? This is compiled with g++ (3.4) sucessfully.
int main() { int x = 12; char pz[x]; }
Solution 1:
Here's your combination answer of all these other ones:
Your code right now is not standard C++. It is standard C99. This is because C99 allows you to declare arrays dynamically that way. To clarify, this is also standard C99:
#include <stdio.h>
int main()
{
int x = 0;
scanf("%d", &x);
char pz[x];
}
This is not standard anything:
#include <iostream>
int main()
{
int x = 0;
std::cin >> x;
char pz[x];
}
It cannot be standard C++ because that required constant array sizes, and it cannot be standard C because C does not have std::cin
(or namespaces, or classes, etc...)
To make it standard C++, do this:
int main()
{
const int x = 12; // x is 12 now and forever...
char pz[x]; // ...therefore it can be used here
}
If you want a dynamic array, you can do this:
#include <iostream>
int main()
{
int x = 0;
std::cin >> x;
char *pz = new char[x];
delete [] pz;
}
But you should do this:
#include <iostream>
#include <vector>
int main()
{
int x = 0;
std::cin >> x;
std::vector<char> pz(x);
}
Solution 2:
Technically, this isn't part of C++. You can do variable length arrays in C99 (ISO/IEC 9899:1999) but they are not part of C++. As you've discovered, they are supported as an extension by some compilers.
Solution 3:
G++ supports a C99 feature that allows dynamically sized arrays. It is not standard C++. G++ has the -ansi
option that turns off some features that aren't in C++, but this isn't one of them. To make G++ reject that code, use the -pedantic
option:
$ g++ -pedantic junk.cpp junk.cpp: In function ‘int main()’: junk.cpp:4: error: ISO C++ forbids variable-size array ‘pz’
Solution 4:
If you want a dynamic array on the stack:
void dynArray(int x)
{
int *array = (int *)alloca(sizeof(*array)*x);
// blah blah blah..
}