I want to declare and initialize a pointer, with a value (like 1000) and I don’t wanna use second variable. Please see below :
int *p = &1000;
Output: error : & on Constant
int *p = (int *)1000;
Output: 0000003E8
int *p = new int(1000);
Output: 1000
Since, first two methods are not giving the expected output. So, I would like to know, which one would be the correct method and why ?
According to your comment,
you would like to initialize the pointer such that it points to a place that stores the integer
1000. You do not want to initialize the pointer such that it points to the absolute address1000.Of the three lines of code you offered, only the last one does what you want:
This allocates space for an
inton the heap and value-initializes that space with1000.Notes:
Allocating space for a single
inton the heap may sometimes be necessary, but most of the time it won’t be useful, because anintis a very small object. The pointer may very well be just as large or larger, therefore passing around a pointer to anint, rather than passing around theintitself, is of limited use.If you really think you need this, keep in mind that you’ll need to deallocate that space later, using
On a general note, most of the time you need to allocate space on the heap and maintain pointers to it, you are far better off using smart pointers (such as
std::unique_ptr<int>orstd::shared_ptr<int>in C++11) to avoid having to think of deallocation.