You are here:

C++/Pointer Initializaton

Advertisement


Question
Hi Vijay ,

I have some basic doubt , Here it is

int p=2;
int *t=&p; // This will work  (Here &p is 3452 )
int *t=p ;  // why this will fail (Here P is 2)
*t = p;  // why this will work fine (Here p is 2)
int *t=6;  // why this will fail (Here we are assigning 6)

int &r= &p; // why this will fail (Here &p is 3452)

int &r = p;  // why this will work  (Here p is 2)

in all the above casess either p or &p or some int value all these are int values only but in some conditions why it is failing

Many thanks in Advance,  

Answer
int p=2;
int *t=&p; // This will work  (Here &p is 3452 )
This is fine. t is a pointer to an int; ie. it contains the address of an int. &p is the address of p which is an int.

int p=2;
int *t=p ;  // why this will fail (Here P is 2)
This fails. As before t is a pointer to an int; ie. it contains the address of an int. because p is an int, not an address of an int this is incorrect.

*t = p;  // why this will work fine (Here p is 2)
This is fine, t is a pointer to an int; ie. it contains the address of an int. *t is the reference to the int whose address is in t. We can assign one int to another int.

int *t=6;  // why this will fail (Here we are assigning 6)
This fails. As before t is a pointer to an int; ie. it contains the address of an int. because 6 is a const  int, not the address of an int this is incorrect.

int p=2;
int &r= &p; // why this will fail (Here &p is 3452)
This fails. r is a reference to an int; ie. it is an alias for an int. &p is the address of p which is a pointer to an int. But r is not an alias for a pointer.

int p=2;
int &r = p;  // why this will work  (Here p is 2)
This is fine. As before, r is a reference to an int; ie. it is an alias for an int. p is an int and r is initialized as an alias for the int p.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.