Advertisement

Passing an array to a class function

Started by March 17, 2001 06:52 PM
1 comment, last by ThaUnknownProgga 23 years, 10 months ago
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:
  //either:int theFunction(int array[])//or:int theFunction(int *array)  


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

Harry.
Harry.
Advertisement
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);
}

This topic is closed to new replies.

Advertisement