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 delete
ing 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}});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With