1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
int *a,
b;
/*
This defines a pointer to an integer and an integer (b IS NOT A POINTER).
When in a declaration, * acts as syntax (it's not quite an operator) and
declares the identifier as a pointer to the type to its left. So 'int' is an
integer, 'int *' is a pointer to an integer, 'int **' is a pointer to a pointer
to an integer, etc.
*/
int *c,
*d;
//In this case case, both c and d are pointers.
std::cout <<a<<std::endl;
/*
OK. Although a is uninitialized, it still has a value. Some environments
(Visual C++, for instance), however, will complain if you try ro get the value
from an uninitialized variable. If it doesn't, this will print a hexadecimal
number like 0xABCDEF01.
*/
std::cout <<*a<<std::endl;
/*
This is dereferencing. When the * operator is in an expression, it acts as the
dereference operator, and gives the variable or object at the memory address
the pointer points to.
However, this is incorrect because a is uninitialized and points to an unknown
(and probably invalid). The least that can happen is that you get garbage. In
this case, the worst is that you produce a segmentation fault because you tried
to access memory outside of your segment (the memory allocated for your
program).
*/
(*a)++;
/*
This, on the other hand, is very dangerous. You'll be lucky to get a
segmentation fault. If you don't, you could be writing to an unknown address
with unpredictable results.
The general rule is: is you don't initialize pointer immediately, set them to
zero or NULL (if (!pointer) or if (pointer == NULL)) so that you can easily test
if they're valid. Never dereference invalid pointers.
*/
a=new int;
/*
Now a points to a valid memory address. I can't remember ATM if the value
pointed to is initialized or not. Let's suppose it's initialized to zero.
*/
std::cout <<*a<<std::endl;
//And now, this prints a zero.
(*a)++;
//And this is also valid now. a now points to a 1.
|