C++ - sending an array to a function

Started by
6 comments, last by DevFred 15 years, 8 months ago
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 :)
Advertisement
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?
i couldn't spot the memory leak can you show it ?
Quote:Original post by neurorebel
i couldn't spot the memory leak can you show it ?
Think about what happens if foo throws an exception.
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
Holy crap, you can read!
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.
Mike Popoloski | Journal | SlimDX
We just had a discussion about array passing in C, maybe that helps you.

This topic is closed to new replies.

Advertisement