new int initialization

 
int *x = new int(5);


why can't I do,

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



also,

1
2
3
int *x = new int(5);
cout << x << endl;
cout << &x << endl;


why is this not printing 5?
I am assuming you are trying to code some dynamic memory allocation, or do you just want your variable x to equal 5?
I want to assign variable x equal to 5 but also using dynamic allocation.
why can't I do,

x = 5;


Because 'x' is a pointer. You cannot [normally] assign an integer value to a pointer. You assign it to an integer.

1
2
3
4
5
6
7
8
9
10
11
// why is this not printing 5

int *x = new int(5);
cout << x << endl;   // <- x is a pointer.  This prints the contents of the pointer, which is an address
cout << &x << endl;  // <- this prints the address of x

cout << *x << endl; // <- this "dereferences" x (that is, looks at what it points to), so this will print 5


// you could also do this to assign it:
*x = 5;
Last edited on
1
2
int *x = new int;
x = 5;


you are assigning 5 to the actual adress.
this will do
*x = 5

1
2
3
int *x = new int(5);
cout << x << endl;
cout << &x << endl;

you should dereference it to see whats inside the adress of x
this will doo
1
2
std::cout << *x << std::endl;
std::cout << *&x << std::endl;
Topic archived. No new replies allowed.