Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing static array to function in C++

Tags:

c++

visual-c++

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++?

like image 756
xori Avatar asked Oct 16 '12 04:10

xori


2 Answers

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}});
}
like image 92
Jesse Good Avatar answered Oct 27 '22 22:10

Jesse Good


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.

like image 21
ValekHalfHeart Avatar answered Oct 27 '22 23:10

ValekHalfHeart