XII-B-CS (A NOTE ON--POINTER)--PART 1
Pointers
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Syllabus:
Declaration and Initialization of Pointers; Dynamic memory allocation/deallocation operators:
new, delete; Pointers and Arrays: Array of Pointers, Pointer to an array (1 dimensional array), Function returning a pointer, Reference variables and use of alias; Function call by reference. Pointer to structures:Deference operator: *, ->; self referencial structures;
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Introduction: A pointer is a variable which holds a memory address of another variable. Any variable declared in a program has two components: Location name | | p |
Value at location | | 21 |
Location | | 1001 (suppose actual physical address) |
When the amount of memory to be allocated is known in advance and memory is allocated during compilation, it is referred to as static memory allocation. For example:
int a=10;
Dynamic Memory Allocation:
When the amount of memory to be allocated is not known in advance and memory is allocated during execution, it is referred to as dynamic memory allocation. There are two operators new and delete in C++ for dynamic memory allocation. The operator new allocates memory dynamically whereas the operator delete is used for deallocation, when the memory is no longer in use.
Declaration and Initialization of Pointers:
A pointer variable name is preceded by an asterisk (*) sign. The data type of the pointer should be the same as the data type of the variable to which it will point.
Syntax: type *var_name;
Example:
int *iptr; //declaration of an integer pointer
int p = 21;
iptr= &p; //iptr stores the address of integer variable p
C++ has two unary operators for referencing to the components of any variable. & (address operator) returns the address of the variable and * (indirection operator) returns the value stored at any address in the memory. Address of p | | 1050 | int p =21, j; |
p | | 21 | int * iptr; |
iptr | | 1050 | iptr=&p; |
j | | 21 | j=p; |