|
Pointers:
Pointers are useful in manipulating computer
memory thus simplifies many tasks in programming, such as sorting
arrays; however, the actual benefits of pointers are beyond the
scope of this tutorial. Nevertheless, it is still useful to get a
glimpse of what they are, and what they basically do. As the name
implies, a pointer acts as a reference point to memory. In fact,
the seekg() and seekp() functions you saw in the file stream
section were pointer functions that point to a specific location
in a file loaded into memory. For now note the use of the asterisk
* and ampersand &.
Okay, lets go over some basic concepts of pointers with the
following example:
int *ptr;
//ptr is now a pointer variable, note the use of *
int x = 3;
ptr = &x;
//&x gives the memory address of x instead of the value
it holds
//now pointer ptr points directly to x in memory
cout << ptr << endl;
//outputs the memory address, something similar to
this:
//0x0064fe00 which is also the address of &x
cout << *ptr << endl; //outputs the value that address holds,
which is 3
*ptr += 3;
//add 3 to itself through dereferencing
cout << *ptr << endl;
//now the value becomes 6
One way to use pointers is to pass function parameters by
reference. For example:
#include <iostream.h>
void sum(int x, int y,
int &sum)
{
sum=x+y;
}
int main()
{
int sum;
sum(4,7,sum);
cout
<< sum;
return 0;
}
In this example, even though the value of sum is not
returned by the function, the void sum() function makes direct
change to the memory location of variable sum in the main
function, because it is passed to void sum() by reference. Passing
by reference is often used to save computer memory on big
arguments like an array or a matrix. The const
statement is sometimes used to make sure
variables passed by reference are not modified by the function,
when they are not meant to be modified. Such as:
int sum(const int
&x, const int &y, int &sum)
Now no matter what you do to x and y within
the function, you cannot change x and y in any way.
For this tutorial, thats about it for pointers, if you are serious
about learning pointers, which is important in advance C++
programming, please check our reference page for more information.
THE END |