Here's a little background info on passing to function. When you call a function, all the parameters you send to it are copied and given to the function to use. This means that if a function makes changes to the variables it is given, they won't be changed anywhere but inside that function. For instance, look at the following code: #include <iostream.h> void change_values(int a, int b) { a = 4; b = 5; } void main(void) { int a; int b; a = 1; b = 2; change_values(a,b); cout << "A is " << a << ", B is " << b << "\n"; } Here's the output of this program: A is 1, B is 2
Note that the call to
Don't give a function data, give a function pointers to data.So how can we do that? Well, remember that the & operator gives you the address of where a variable is inside your computer; or more to the point, it gives you a pointer to the data. Armed with this knowledge, let's redo the above program: #include <iostream.h> void change_values(int *a, int *b) { *a = 4; *b = 5; } void main(void) { int a; int b; a = 1; b = 2; change_values(&a,&b); cout << "A is " << a << ", B is " << b << "\n"; } And behold! The gods of C++ smile, and you are presented with: A is 4, B is 5
Take a look at the above code, and make sure you understand what's going on.
The |