-1
int *x = new int;
*x = 5;

cout << x << endl;
delete[] x;

I am trying to dynamically allocate resources to a variable 'x'. I then assign the value '5' to it. When I try to print the value of 'x', I get some garbage value called 0x8321 and so on. I am sure that is not the value I assigned.

Any idea how I can access the value of x?

theprogrammer
  • 177
  • 1
  • 1
  • 10

2 Answers2

3

You must use std::cout << *x << std::endl.

The value that you are getting is the address of the memory (region) to where the pointer is pointing to.

EDIT : And use delete x; instead of delete[] x;.

  • 1
    also don't forget to `delete x;` instead of `delete[] x'` – dmi Feb 24 '17 at 12:27
  • Yes, made changes to the answer accordingly. –  Feb 24 '17 at 12:29
  • 1
    Using-directives in files where main function is defined isn't bad practice, often the opposite, i.e. using _std::_ all over the program is. – Klaus Feb 24 '17 at 12:36
  • he was right. i was indeed using 'using namespace std' – theprogrammer Feb 24 '17 at 12:39
  • See [Why is "using namespace std" considered bad practice ?](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Garf365 Feb 24 '17 at 13:00
1

You are currently printing the address of the pointer. If you want the value you should do cout << *x << endl

Chris
  • 23
  • 5