C++ - sending an array to a function
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 :)
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);
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?
Quote:Original post by neurorebelThink about what happens if foo throws an exception.
i couldn't spot the memory leak can you show it ?
That and array1 is filled with stuff and hasn't set it's values to 0 or NULL, correct?
But yeah... arrays. Thought you could trust 'em, huh? You must learn to become one with the namespace of std. :]
~Maverick
But yeah... arrays. Thought you could trust 'em, huh? You must learn to become one with the namespace of std. :]
~Maverick
Quote:Original post by PCN
That and array1 is filled with stuff and hasn't set it's values to 0 or NULL, correct?
That's not a memory leak, and may not even be a problem, depending on the design of the program.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement