Okay Dumb it down a little because I have no idea what you just said. To be honest I still dont understand pointers very well. I know they are variables that point to different variables.
|
No, pointers point to addresses in memory. If that address happens to be the address of a variable, then all is good.
Some elaboration:
int *x_ptr;
int x;
x_ptr = &x; // & is a reference or "address of" operator here.
x_ptr points to the address where x is located. You can access x through x_ptr by dereferencing it: y = *x_ptr * 2;
The * on x_ptr tells the compiler you want to access what is stored at the address x_ptr points to. Without the *, you are getting the address it points to.
You can do this with classes and structures (essentially public classes) just as well:
Triangle *tri_ptr;
Triangle tri;
tri_ptr = &tri;
Function names are no more than a symbolic name for the address where that function's code begins, similar to a variable name. A variable name is really nothing more than a symbolic name for an address in memory. So you can make a pointer to a function and treat it as a variable:
int addition(int a, int b);
int (*mathop)(int, int) = addition;
Assigns the address of the function addition to the "variable" mathop.
Note, that the prototype for the function to be called must match the prototype for the function pointer: two int arguments, returning an int.
Instead of assigning addition to the function pointer mathop, you can pass the function name to a function that accepts pointers to function. This is called a call back function.
m = operation (7, 5, addition);
Passes the name(address) of addition to the function "operation."
int operation (int x, int y, int (*functocall)(int,int))
Operation accepts two integers and a pointer to a function that accepts two integers and returns an int.
Operation then calls "functocall" with the two integers passed to operation and receives the integer returned by the function call. In this case, the function "addition."
If you're still not getting it, I'll try some pictures.