All these are fine suggestions, but are overkill for what you want to do. You seem to understand what a pointer is, so I''ll skip any explanation.
I will how ever explain the reference operator ''&''.
Snippets from an Article I wrote:
Reference Operator & The "reference operator" or "address-of operator" exposes the memory address of the variable to which it is prefixed. The ''&'' operator specifies that the memory address of the variable should be retrieved and assigned to the pointer, not the contents of the variable. This distinction is crucial.
Passing References to Functions Here''s a more practical application of using a pointer:
int main(void){ int hello = 0; SomeFunction(&hello); return 0;}void SomeFunction(int* value){ (*value) ++;}
A pointer, or reference, to our variable was passed to the function and the function wrote to that address. This approach is particularly useful for large variables, such as structures, in that you don''t have to copy those variables in their entirety to the function and then copy them back in order to return them. It is also well suited for use with functions that need to return several variables at once.
Here''s an example of a function that returns values for more than one variable. Since C++ only supports returning one value at a time, we pass a reference to the second variable that we want to fill and then dereference it inside the function.
int Difference( int a, int b, bool* isNegative){ *isNegative = false; // dereference isNegative in order to set the value stored at that address to false in case our if conditional fails int retvalue = 0; retvalue = a - b; if(retvalue < 0) *isNegative = true; //If true we change the bool value stored at the address pointed to by isNegative to true return retvalue; //return the difference}
Hopefully this article will be posted soon.
-James