Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

Pointers

Pointers are the powerful feature of C++ programming which differs it from other popular programming languages like: Java, Visual Basic etc.
To understand pointers, you should have the knowledge of address in computer memory. Computer memory is broken down into bytes and each byte has its own address. For example: In 1KB memory, there are 1024 bytes and each byte is given an address (0 - 1023).

The Address-of Operator &

The & operator can find address occupied by a variable. If var is a variable then, &vargives the address of that variable.

Example 1: Address-of Operator

#include <iostream>
using namespace std;

int main() {
    int var1 = 3;
    int var2 = 24;
    int var3 = 17;
    cout<<&var1<<endl;
    cout<<&var2<<endl;
    cout<<&var3<<endl;

}
Output
0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4
The 0x in the beginning represents the address is in hexadecimal form. (You may not get the same result on your system.). Notice that first address differs from second by 4-bytes and second address differs from third by 4-bytes. It is because the size of integer(variable of type int) is 4 bytes in 64-bit system.

No comments:

Post a Comment