Pointers are a tool available in C++ for giving you more control over a computers memory. Important uses of pointers include dynamic memory allocation and linked data structures. They can also be used for manipulating data in arrays and in functions for reference parameters.
The address operator & can be used to view the address of a variable.
Example: Print the address of a variable.
# include<iostream>
|
A reference is a synonym or an alias for another variable. When one variable name is declared to be a reference for another, both variable names refer to the same location in memory. Changing the value of one variable changes the value of the other variable. Reference variables can be created using the reference & operator. Note: (1) References are pointer constants and (2) The & operator is overloaded to access addresses and create references.
Example: References as aliases.
# include<iostream>
|
Example: Passing by reference.
# include<iostream>
int main( ) void circle (double radius, double &perimeter, double &area) |
A pointer is a variable that stores a memory address. A pointer may be declared using the * operator.
All pointers should be initialized to the address of another variable. If the address of another variable is not available yet, set the pointer to null.
The dereference operator * can be used to obtain the value to which the pointer points. Note the * operator has been overloaded to (i) multiply several different data types (ii) declare a pointer and (iii) dereference a pointer.
Example: Declare and initialize a pointer variable. Point to different places in memory. Dereference a pointer.
|
An array name is a constant pointer to the first element of an array. In the example below, data is a pointer to &data[0].
Example: Using pointers to traverse an array.
# include<iostream>
|
Example: Dynamic memory allocation.
# include<iostream> |