Sign in to follow this  
SmokeN

C++ - sending an array to a function

Recommended Posts

Hello everyone, I'm new here, I'm studying these days how to program in C++ and I don't really understand how to send an array\2d array to a function, I've tried to look on some tutorials over the net but didn't really get it. Would be nice if someone can write here an example of how exactly it should be done. Thanks in advance, have a nice day :)

Share this post


Link to post
Share on other sites
Arrays are passed by reference. For instance:
void foo(int (&a)[10]) { a[2] = 10; }
int array[10];
foo(array);

void bar(int (&b)[10][20]) { b[3][7] = 42; }
int array[10][20];
bar(array);


Share this post


Link to post
Share on other sites

void foo( int * array ) {
// Do stuff
}

void bar() {
int array1[50];
int * array2 = new int[50]

foo( array1 );
foo( array2 );

delete[] array2;
}



But, really, save yourself a lot of hassle and get used to doing

void foo( std::vector< int > const& array ) {
// Do stuff
}

void bar() {
std::vector< int > array;

foo( array );
}



Btw. can you spot the potential memory leak in my first example?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this