Passing an array to a class function
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?
Pass array as int [] or int* in the function header. Like this:
They''re both the same as far as the compiler''s concerned.
Harry.
|
They''re both the same as far as the compiler''s concerned.
Harry.
Harry.
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);
}
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);
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement