Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

ThaUnknownProgga

Passing an array to a class function

This topic is 6363 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

I have an array which i initialize (array = new int[3]) in my main code file. I want to pass this to a class''s member function. What''s the proper syntax for doing this so that i can access the contents of the array in the class''s function?

Share this post


Link to post
Share on other sites
Advertisement
Pass array as int [] or int* in the function header. Like this:
  
//either:

int theFunction(int array[])

//or:

int theFunction(int *array)


They''re both the same as far as the compiler''s concerned.

Harry.

Share this post


Link to post
Share on other sites
Since array is defined as int*, or pointer to int, you can simply pass it by value. Your "array" variable is the address of the 3 ints vector, so with this address every function (class method or not) can get to the three ints :


class ThreeInt
{
private:
int m_v[3];
public:
void getInts (int* v);
};

void ThreeInt::getInts (int* v)
{
m_v[0] = v[0];
m_v[1] = v[1];
m_v[2] = v[2];
}


void main (void)
{
ThreeInt a;
int* array = new int[3];
array[0] = 0; array[1] = 1; array[2] = 2;
a.getInts (array);
}

Share this post


Link to post
Share on other sites

  • 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!