Lecture 1.4
Lecture 1.4
7
Dangling Pointers
int * fun( )
{
int x=10;
return &x;
}
int main()
{
int *ptr=fun( ); //ptr points to address of x. Here ptr is
dangling pointer.
} 8
Dangling pointers
Depending on a particular system, after the delete p;
statement executes, the pointer variable might still contain
the addresses of the deallocated memory space. In this case
we say that these pointers are dangling.
One way to avoid this pitfall is to set these pointers to
NULL after the delete operation.
int *p;
p = new int;
*p = 34;
delete p;
p = NULL;
p = new int;
*p = 60;
Dynamic Two-Dimensional Arrays
int **board;
This statement declares board to be a pointer to a pointer. In
other words, board and *board are pointers. Now board can
store the address of a pointer or an array of pointers of type
int, and *board can store the address of an int memory space or
an array of int values.
Dynamic Two-Dimensional Arrays
Suppose that you want board to be an array of 10 rows and
15 columns. To accomplish this, first we create an array of
10 pointers of type int and assign the address of that array
to board.
board = new int*[10];
Next we create the columns of board. The following for
loop accomplish this:
for(int row = 0; row < 10; row++)
Board[row] = new int[15];
Number of rows and number of columns of board can
be specified during program execution.
Dynamic Arrays Example
1. Every recursive definition must have one (or more) base cases
fact (1)
num==1
Because sum != 0
return 1 * fact (0);
fact (0)
num==0
Because sum is 0
return 1;
Direct and Indirect Recursion
Direct recursion: When function calls itself, it is called direct
recursion, the example we have seen previously is a direct recursion
example.
Indirect recursion: When function calls