Pointers

by Shabbir on May 3, 2008

in C/C++

Pointers are one of the hardest parts of programming to understand. But they are very useful.
When programming with pointers, we use two operators: reference operator (&) and dereference operator (*).
We use the reference operator to see the address where a variable is stored, and the dereference operator is to see the value of a variable.

Example:

int a = 10;
int *ptr = &a;
 
cout << ptr << endl;       //Will print the address of a in hex
cout << *ptr << endl;      //Will print the value of a (10)
 
//ptr = a;      This is wrong

Now, the addres of the variable a is stored in ptr, this means that ptr shows on a. According to this we can change the value of a using ptr.

See this example:

*ptr = 20;
cout << a << endl;      //Will print 20

Pointers and variables in memory

As you see on the picture, the variable a is stored on the memory location 0002 with its value 10, and ptr is stored on the memory location 0005 and its value is the address of variable a (0002). This explains the above example.

In one the next articles we will explain using pointers with arrays, so stay tuned.

Sharing is Caring...

Other Related Posts:

  1. Pointers and Arrays
  2. Increment and Decrement Operators
  3. Functions in C++
  4. Read From File In C++
  5. Write To File In C++

Leave a Comment

Spam protection by WP Captcha-Free

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.