Ciaran Wickham Ciaran Wickham - 1 month ago 7
C++ Question

How to reference int pointers

How to reference an integer pointer in C++ (visual studio), something like:

int * ptr = 5;
std::cout << *ptr << std::endl;


Without getting the error: identifier
ptr
is undefined

Answer

You said "reference an integer pointer" which sounds to me like:

int* ptr = new int;
*ptr=5;
int*& ref_to_ptr = ptr;

However, I do not think you meant that. You meant something like this:

int* ptr = new int(5);
std::cout << *ptr;

When you assign 5 to ptr directly without new, you are trying to give it an address rather than a value. Pointers holds an address to some place where the value exist rather than holding a a direct value.

See this for more information: http://www.cplusplus.com/doc/tutorial/pointers/