1

I have just been starting with C++ and I have come across multiple types of array declaration in C++

int data[3];

and other type is,

int *data= new data[3];

What is the difference between the two? Since, I have not allocated memory in the first case will I overwrite memory which may already be in use and potentially cause segmentation error?

  • 2
    In the first case, `data` is declared with *automatic* storage duration and its life only extends while the current scope is defined. So if you declare `int data[3];` within a function, it can be used in that function, but after the function returns, the function stack is destroyed and there can be no further reference to that `data`. In the second case you dynamically allocate storage for `data[3]` using the `new` operator. Dynamic storage duration extends from the time of allocated until it is de-allocated. So you can declare/allocate in a function and the memory survives the function return – David C. Rankin Feb 10 '18 at 10:18
  • Otherwise, you get an array of 3 `int` out of either -- the only difference is how long they live and that no more that 3 elements will ever make up the 1st case, while you can resize the array in the 2nd case if you need to add more elements. – David C. Rankin Feb 10 '18 at 10:20

0 Answers0