|
|
|
|
|
|
|
int* Func()
{
int n;
.
.
.
return &n;
} |
|
|
|
|
|
|
|
|
Remember that automatic variables are implicitly created at block entry and implicitly destroyed at block exit. The above function returns a pointer to the local variable n, but n disappears as soon as control exits the function. The caller of the function therefore receives a dangling pointer. Dangling pointers are hazardous for the same reason that uninitialized pointers are hazardous: when your program dereferences incorrect pointer values, it will access memory locations whose contents are unknown. |
|
|
|
|
|
|
|
|
Testing and Debugging Hints |
|
|
|
|
|
|
|
|
1. To declare two pointer variables in the same statement, you must use |
|
|
|
 |
|
|
|
|
int *p, *q; |
|
|
|
 |
|
|
|
|
You cannot use |
|
|
|
 |
|
|
|
|
int* p, q; |
|
|
|
 |
|
|
|
|
Similarly, you must use |
|
|
|
 |
|
|
|
|
int &m, &n; |
|
|
|
 |
|
|
|
|
to declare two reference variables in the same statement. |
|
|
|
|
|
|
|
|
2. Do not confuse a pointer with the variable it points to. |
|
|
|
|
|
|
|
|
3. Before dereferencing a pointer variable, be sure it has been assigned a meaningful value other than NULL. |
|
|
|
|
|
|
|
|
4. Pointer variables must be of the same data type to be compared or assigned to one another. |
|
|
|
|
|
|
|
|
5. In an expression, an array name without any index brackets is a pointer expression; its value is the base address of the array. The array name is considered a constant expression, so it cannot be assigned to. The following code shows correct and incorrect assignments. |
|
|
|
|
|