-6

basic syntax of pointers: *ptr= &a

here &a will return the memory address of variable a and *ptr will store value of variable a

I want to ask, is it possible to make a pointer return a value from a given memory address? if yes what's the syntax

Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43

2 Answers2

1

Yes, you can construct a pointer that refers to some arbitrary address in memory, by initialising the pointer with the address directly, instead of with an expression like &a:

int* ptr = (int*)0x1234ABCD;  // hex for convenience
std::cout << *ptr;

Be careful, though, as it is rare that you know such a memory address exactly.

The cast (int*) is required as no implicit conversion exists between int and int*.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Yes. Use the dereference operator *. For example;

int * a = new int;
int * b = new int;
*a = 5;
// Now a points to a memory location where the number 5 is stored.
b = a; //b now points to the same memory location.
cout << *b << endl; ///prints 5.
cout << a << " " << b << endl; //prints the same address.

int * c = new int;
c = *a;
// Now c points to another memory location than a, but the value is the same.
cout << *c << endl; ///prints 5.
cout << a << " " << c << endl; //prints different addresses.
riklund
  • 1,031
  • 2
  • 8
  • 16