Jump to content
  • Advertisement
Sign in to follow this  
SmokeN

C++ - sending an array to a function

This topic is 3731 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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);


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
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!