Pointers

Declaration of a pointer

int *p;
int a=10;

int is not the datatype of pointer as pointer points to the address of the memory location. Therefore, it is the data type of the content stored at that address.

*p is how you declare the pointer. Just like you declare any other variable (say p as int p or a as int a), a pointer is preceded by an asterik (*). Note that ‘a’ is an integer type and ‘p’ is a pointer.

Assign value to a pointer

p=&a;

As we know & refers to the address when we use it before the variable name, Therefore this statement means get the address of ‘a’ and store it in ‘p’. It will not store the value of ‘a’ (which is 10) in p, In fact, it will store the address of ‘a’ in ‘p’. Now we can say that ‘p’ points to ‘a’. As shown below address of a is 1004 so p stores 1004 or it points to 1004.

Changing contents of variable using a pointer

Now if we want to change the value of ‘a’ using the pointer, we will do it this way:

*p=15;

This means set the value ’15’ stored at the address which is pointed at by ‘p’. As ‘p’ points to 1004, it will go to 1004 and update the value stored at that address i.e. update the value of ‘a’ to 15 which was 10 earlier.

Summing it up, the program looks like this:

int a=10; int*p; //a=10
p=&a; //p=1004, a=10
*p=15; //p=1004,a=15

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a free website or blog at WordPress.com.

Up ↑

Create your website at WordPress.com
Get started
%d bloggers like this: