Pointers


A pointer is a variable that contains the memory location of another variable. Syntax:- type * variable name  You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. Declaration To declare ptr as an integer pointer: int *ptr; To declare ptr as a character pointer: char *ptr;

Operation on Pointers


Valid operations on pointers include: - the sum of a pointer and an integer - the difference of a pointer and an integer - pointer comparison the difference of two pointers. Increment/decrement in pointers assignment operator used in pointers
            void main()
            {
             int a=25,b=78,sum;
             int *x,*y;
             x=&a;
             y=&b;
              sum= *x + *y;
             cout<<“Sum is : ”<
    

Types of Pointers


1. Dangling Pointer
Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data.
2. Null Pointer
A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type. int * p; p = 0; // p has a null pointer value 3. Wild Pointer
Wild pointers arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behaviour as dangling pointers, though they are less likely to stay undetected. The wild pointer generates garbage memory location and pendent refernce.

causes:


  • Pointer declared but not initialized
  • Pointer alteration
  • Accessing destroyed data

4. Void Pointer
When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to typecast it to another kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different types at different times. Syntax: void * variable name;