0

I have been working on C++ and I was recently told that I was making 2D arrays on the heap wrong. I have always done it this way:

int **array1 = new int*[200];
for (int i = 0; i < 200; ++i)
{
    array1[i] = new int[200];
}

I was told that this was the better way:

int(*ptr)[200] = new int[200][200];

However the person explaining it to me was not able to explain it well as to why one is better then the other. I was hoping someone here would tell me why one would be better then the other?

  • 1
    Is there a reason you can't use an `std::vector` or `std::array`? – scohe001 Nov 26 '18 at 22:39
  • I would in most cases but I just was wondering why one be better then the other if for some reason you were forced. – xxcellerator Nov 26 '18 at 22:40
  • 1
    The second only makes one allocation, so it'll be faster at runtime. Might even be drastically faster in multi-threaded code with a single thread allocator. Though neither are something you should ever really find yourself writing unless using a legacy system. – George Nov 26 '18 at 22:43
  • 1
    `int(*ptr)[200] = new int[200][200];` only works if you know the second dimension at compile time. Instead I suggest [a simple matrix class](https://stackoverflow.com/a/2076668/4581301). – user4581301 Nov 26 '18 at 22:57
  • Here's an article why you should reduce the number of calls to dynamic memory (on windows) https://randomascii.wordpress.com/2014/12/10/hidden-costs-of-memory-allocation/ If you're not planning on freeing all of the elements at the same time, you could go towards fragmentation. If you're planning on freeing all of the elements at the same time, you're probably better off using the "better way* structure to be more clear about your intentions. – GandhiGandhi Nov 27 '18 at 00:27
  • Thank you for the answers and the article link it was very helpful. – xxcellerator Nov 27 '18 at 18:21

0 Answers0