Archived

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

ThaUnknownProgga

Passing an array to a class function

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
HarryW    226
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
Diodor    517
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