Pointers

What are pointers?

A pointer is a variable that holds a memory address.
This address is the location of another object (variable or anything) in memory.
For example, if one variable contains the address of another variable, the first variable is said to point to second.

Advantages and disadvantages of pointers

Advantage

  1. Pointers provide the means by which functions can modify their calling arguments
  2. Pointers support dynamic allocation
  3. Pointers can improve the efficiency of certain routines

Disadvantages

  1. Pointers should be handled with care. Uninitialized pointers can cause system to crash and these bugs are difficult to find

Pointer variables

Syntax

type *name;

type is the base type of pointer and it can be any valid data type.
It defines what type of variables the pointer can point to.
name is the name of pointer variable.

Pointer Operators

The address of operator (&)

The & is a unary operator that returns the memory address of its operand.

For Example,

m = &count;

places into m the memory address of variable count.
This address is the computer’s internal location of the variable.
It has nothing to do with value of count.
For better understanding, assume that the variable count uses memory location 2000 to store its value.
Also say that the value of count is 100.
Than after the above assignment m will have 2000.
(Not the value of count, but the memory address)

Dereference operator (*)

It is the complement of above operator.
It is a unary operator that returns the value located at the address that follows.
Continuing the above example, if m contains the memory address of variable count than,
q = *m;

places the value of count into q.
Thus, q will have value 100 because 100 is stores at location 2000, which is the memory address that is stores in m.

Important Note

When we declare a pointer to be of type int, the compiler assumes that the address it holds points an integer variable.
In C++, it is illegal to convert one type of pointer into another without the use of an explicit type cast.
When we don’t assign the pointer to a matching data type variable, the program compiles error free but does not produce desired results.

Example,

#include<iostream>
using namespace std;

int main()
{
    double x = 100.1,y;
    int *p;

    p = (int *)&x;
    y = *p;
    
    cout<<y;
    return 0;
}

This program does not print 100.1 because some bits are lost due to incorrect pointer data type

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?