Pointers in C++ By Vikram Uday Kulkarni MBA (Systems)
What is Pointer • What exactly is a pointer variable? it's a variable that holds the address of another variable, function or data.
Understanding Memory Address • All computers have memory, also known as RAM. RAM holds the programs that your computer is currently running along with the data they are currently manipulating (their variables and data structures). Memory can be thought of simply as an array of bytes.
Understanding Memory Address • In this array, every memory location has its own address -- the address of the first byte is 0, followed by 1, 2, 3, and so on. Memory addresses act just like the indexes of a normal array. The computer can access any address in memory at any time (hence the name "random access memory"). It can also group bytes together as it needs to form larger
Understanding Memory Address • Example float f; • This statement says, "Declare a location named f that can hold one floating point value." When the program runs, the computer reserves space for the variable f somewhere in memory. That location has a fixed address in the memory space, like
Variable Declaration
Understanding Memory Address • While you think of the variable f, the computer thinks of a specific address in memory (for example, 248,440). Therefore, when you create a statement like this: f = 3.14; • The compiler might translate that into, "Load the value 3.14 into memory location 248,440." The computer is always thinking of memory in terms of
Variable With Value
Syntax of Pointer Declaration • The * character is used to refer to a pointer. int
; // Declare a variable int *; // Declare a pointer to above variable
Example
int a=46; int *d=&a;
Here a is a variable and d is pointer variable ‘*d’ points to the address of variable ‘a’.
Example #include int main() { int I; int j; int *p; //a pointer to an integer cout<
• This code tells the compiler to print out the address held in p, along with the address of i. The variable p starts off with some crazy value or with 0. The address of i is generally a large value. For example, when I ran this code, I received the following output: 0 2147478276 2147478276 2147478276 WHY is that?