How to Access Memory using Pointer in C++

All the major programming languages provide some excellent tools and APIs to do coding efficiently. Pointers are one of the tools designed to make your codes more efficient and effective. Pointers are used to address the location of a variable in memory hence providing the user to play with unlimited amount of data in his/her program. They are also used to assign memory dynamically, so you do not need to tackle the hassle of knowing how much memory you actually need. They can be used to create and link databases on a very large scale. If you have ever heard about linked-lists then pointers are the main ingredients to create linked lists and ques. I am writing this step by step guide on accessing memory using pointers in C++ that will help you to get familiarize with the syntax and the use of pointers.

Instructions

  • 1

    Syntax: Handling pointers is little tricky as compared to simple variables, because in case of pointers you have to handle the memory location of the variable and also the value stored on that location. Every time you need to declare a pointer, you have to tell the compiler that the variable is going to be a pointer, and it will point to what type of memory. Following syntax is used to declare pointers.


    VariableType  *name_of_pointer;


    For example:


    int  *temp_pointer;


    When you need to declare a pointer, you have to use * sign to tell the compiler that the variable is a pointer.

  • 2

    Pointers are used to point to some variable. In order to do this consider following code lines.


    int a;   // an integer variable


    int *temp_ptr;    // a pointer to sn integer variable.


    temp_ptr = &a;  // now temp_ptr will hold the address of integer a;


    To access or modify the value of a now you can use the pointer and it will automatically modify the value present in integer variable a. It is very important to use & sign to retrieve the address of a certain variable.

  • 3

    Example:


    To clear the use of pointers let's have a look at following example.


    #include


    using namespace std;


    int main()


    {


    int a;


    int *temp_ptr;


    temp_ptr = &a;


    cin>> a;


    cout<< *temp_ptr <<"\n";


    return 0;


    }

  • 4

    The above code is performing a very basic task.  It is simply declaring an integer variable and a pointer to an integer. Once we have saved the address of integer “a” in “temp_ptr”, the pointer will start pointing to a in the memory. Whenever you will call that pointer, it will point towards the value stored in “a” hence in our case we are using “*temp_ptr” to print a value. The compiler will go to that pointer and then pointer will look into address stored in it and will go to variable “a” and hence compiler will print the value stored in "a".


Leave a Reply

Your email address will not be published. Required fields are marked *


7 × eight =