0

whats' the difference when declaring an arrray using int a[100] and int *a = new int[100];? Thanks for you guys answearing my question.

I do understand that the former one will initialize the element in a but the later one won't, and what's more different?

  • This is like asking what is the `stack` and the `heap`. Here are already answers [array on stack and heap](https://stackoverflow.com/questions/1598397/creating-array-of-objects-on-the-stack-and-heap). And here you can learn more about stack and heap: https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap – Eldinur the Kolibri Jul 12 '23 at 08:40
  • 1
    Neither of them will initialise anything in a[]. You also have to delete [] the second one at some point. – lastchance Jul 12 '23 at 08:40
  • 1
    @lastchance that depends on where the declaration is placed. Its different for globals – 463035818_is_not_an_ai Jul 12 '23 at 08:42
  • @463035818_is_not_an_ai, mmm, fair comment; but take my comment to apply to the usual declarations within a function: I don't want to be seen to be encouraging global variables! – lastchance Jul 12 '23 at 08:46

1 Answers1

-2

int a[100] - array placed on stack, program ends if stack limit exceed int *a = new int[100]; - array in heap, exception if no memory

drem1lin
  • 331
  • 1
  • 3
  • 14
  • I think you are making assumptions on where in a program the OP-shown code is. I'd ask for a [mre] instead. The idea that initialisation is involved seems to indicate OP is thinking of global variables. – Yunnosch Jul 12 '23 at 08:40
  • 2
    `int a[100]` isn't necessarily on the stack, c++ calls it local storage. e.g. if that storage is inside a heap allocated object then the array would be on the heap as well – Alan Birtles Jul 12 '23 at 08:43