-8

Is there any difference between these 2 ways of storing an integer?

int X = 100;

and

int *pX = new int(100);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
smwikipedia
  • 61,609
  • 92
  • 309
  • 482

2 Answers2

3

"Is there any difference between these 2 ways of storing an integer?"

Yes, there is a significant difference.

 int X = 100;

Initializes a variable X on the stack with the value 100, while

int *pX = new int(100);

allocates memory for an int on the heap, kept in pointer pX, and initializes the value to 100.

For the latter you should notice, that it's necessary to deallocate that heap memory, when it's no longer needed:

 delete pX;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
2

The first one is creating a variable on the stack while the second one is creating a variable on the heap and creating a pointer to point at it.

Moshe Carmeli
  • 295
  • 1
  • 5