Tuesday, November 29, 2011

Understanding Pointer Variables in C++

Understanding Pointers Variables


A pointer in C++ is an address of a memory location where data is stored. Understanding pointer variables in in C++ provides an opportunity to advance knowledge on how programs access data in memory. A pointer in in C++ provides an indirect way of accessing data in memory. When a variable is declared, the compiler reserves and assigns it a portion of space in memory. This portion of memory is known to the computer by the address associated to it. Knowing the memory address of the variable helps us in understanding pointers in in C++. Once we know this address, we can utilize it using the a reference or a pointer. A pointer variable is defined to point (to store the address of) to the data stored at a specific memory.


Understanding how to Declare and Initialize a Pointer in C++


To understand how to initialize and declare a pointer variable in c++, start with the data type followed by a dereference operator (*) and the name of the variable. Once a C++ pointer has been declared, we assign it with the address of the variable to store. By default, it does not matter how you append the *, as long as it is between the data type and the pointer variable. The name of a pointer variable, must comply with the rules that govern every variable. The value of a declared pointer variable in c++ is the address to which it points. Follow the example below.
      int    *ptr1;                    // pointer to an int
      float   *ptr2;                    // pointer to a float 

Assume we have two variables age and height,we can now store the address of each in our pointer variables  ptr1 and ptr2 respectively as follows:

                ptr1 = &age;       //ptr1 points to age;

                ptr2=&height     //ptr2 points to height;

Read the whole chapter on understanding pointer variables in C++

No comments:

Post a Comment