Introduction to Pointers
Pointers are memory address for variables. Therefore pointers references to other variables.
Pointers indicate where (i.e. what memory address) the variables they reference are.
Declaring pointer variables
Syntax: type *variablename;
Examples:
int *intPtr;
double *myPtr;
char *cp;
float *arrayOfPtrs[10]; // an array of ten pointers to float objects
char **arguments; // a pointer-to-a-pointer-to characters
Pointers can also be initialized at declaration time. For example:
float *fPtr = NULL;
int i = 10; int *ip = &i;
char name[] = "Jim"; char *cPtr = name;
Pointer-related operators: "*" and "&"
The operator "*" has two uses:
In a declaration, *, is used to indicate that a variable is a pointer.
In an assignment statement, *, is used to dereference the pointer, e.g.,
ip is the memory address of i, *ip is the value at the memory address, i.e., 10.
The operator "&" is the address of operator (see example declaration above)
Working with pointers
When we work with other variables we generally have written them as boxes with values inside to represent that variables are named memory which can hold information. For example:
int i = 7; can be represented as
![]()
double d = 23.4 as
![]()
![]()
int
ip = &i;![]()
![]()
The new operator
The new operator provides for storage from a place called the dynamic storage pool or heap
Example: ip = new int; or ip = new int[10]; The first gives you space for one int, the second space for 10 int
The delete operator
The delete operator lets the memory management system know you are finished using the storage which was allocated with new.
Example: To return the storage assigned to ip in the example above use: delete ip; (in the first case, because there is only one int to return) or delete [] ip; (in the second case, because you have an array of 10 int to return)
Examples: