With the defined function as...
void func (int a [3]) { ... }
I'd like to be able to pass a dynamic static array like so
func (new int [3] {1,2,3});
instead of...
int temp [3] = {1,2,3};
func(temp);
Is this possible with C++?
If you have a C++11 compiler, func (new int [3] {1,2,3}); would work fine (but, remember that you are responsible for deleteing the memory). With gcc, just pass the -std=c++11 flag.
However, look into std::array so you don't have to use new:
Example
void func (std::array<int, 3> a)
{
}
int main()
{
func({{1, 2, 3}});
}
delete in the example"std::array are on the stack if you instantiate std::array on the stack. See here. It's basically a struct with an array as a member.It works on my compiler (Eclipse indigo with CDT extension), but it gives a warning that implies it may not work in all environments:
extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
Here's my test code:
void func (int a[3])
{
cout << a[2];
}
int main()
{
func(new int[3]{1,3,8});
}
successfully prints "8" to the console.
Your example with new int [3] {1,2,3} works just fine, but it allocates an array on the heap each time it is called.
You should be able to do it on the stack using a typecast:
func((int[]){1,2,3});
(int[]){1,2,3} is only in C (it's a compound literal).const ... e.g. double arr_func( int n, const double * xs ){ }; arr_func( 3, (const double[]){1.0,2.0,3.0} );
newmeans heap (by default).