Initialization of Pointer

  • Initialization means declaring and assigning.

Syntax :

datatype *variable_name = &variable;

For example :

int *p = &i;

*p = &i;  >>>Here, address of i is stored in *p whereas in above example it is stored in p.

Now we will learn in more detail about this topic:

1.      int i = 10;
        int *p;
        *p = &i;

Here i = 10 is trying to store into *p’s garbage value so that’s not possible. So, above expression is wrong.

2.     int i = 10;
       int *p;
       p = &i;

Here *p has stored the value of i so that is true and that expression will work fine.

3.     int i = 10;
       int *p = i;

Here *p is pointing to 10th address and that is totally wrong.

4.     int i = 10;
       int *p;
       p = i;

Here, same as case 1 :  i = 10 is trying to store into *p’s garbage value so that’s not possible. So, above expression is wrong.

5.     int i = 10;
       int *p = &i;

Here *p has stored the value of i so that is true and this expression will work fine.

6.     int i = 10;
       int *p;
       p = 10;

Here, p is treated as an address so it will not give correct output.

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 )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: