Thursday, July 30, 2009

Returning an array from a function and/or calling the array from another function in the same header file, C++

My problem is that I want to call an array from one function in a header file and then input it into another function in the header file. For example consider the code.





Class MyExample{





private:


double Array1[16], a, b;


int n;





public:





double function1(int n);


double function 2();


};





MyExample::function1(n){





for(a=0;a%26lt;n,a++){


Array1[n] = a;


}


}





MyExample::function 2(){


//I need to get Array1[n] into this function!


for(a=0;a%26lt;n,a++){


Array1[n] = Array1[n]/b;


}


/*


Whats more is that I want to be able to have Array1[n] not be converted to a int because n is an integer.





Also then how would I return Array1[n] to the .c++ file?





Thanks, any help is appreciated as it is getting a bit irritating since I just can't pass the thing.





Brian


*/

Returning an array from a function and/or calling the array from another function in the same header file, C++
Maybe I am not understanding what you are asking, but it looks easy to just pass the array. And pass the value of n - don't use a global.





double Array1[n]


function1(Array1, n);


function2(Array1, n);





void MyExample::function1(double *array, const int size)


{


for (int a = 0; a %26lt; size; a++)


array[a] = a;


}


void MyExample::function 2(double *array, const int size)


{


for (int a = 0; a %26lt; size; a++)


array[a] = array[a]/b;


}





Since you are passing a pointer, you are passing by reference - yes?





And these functions would be typed as void, unless you are returning something not evident in your code.
Reply:You're welcome. Report It

Reply:Define the array globally.
Reply:I'm not sure why you can't just pass the array. You should be able to do:





double * function1(int n);





double function2(double * arrayEntry);





all you will need to do is define the length of the double array globally instead of manually setting it to 16 everywhere, that way the functions become extensible and easier to change.


No comments:

Post a Comment