Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two methods of creating of 2d array

What is the difference between two arrays definitions? Are they realized different in memory?

 int var = 5;
 int (*p4)[2] = new int [var][2]; // first 2d array

 int** p5 = new int*[var];  // second 2d array
 for(int i = 0; i < var; ++i){
     p5[i] = new int[2];
 }   
like image 570
scdmb Avatar asked Mar 11 '26 10:03

scdmb


2 Answers

Yes, they're very different. The first is really a single array; the second is actually var+1 arrays, potentially scattered all over your RAM. var arrays hold the data, and one holds pointers to the var data arrays.

like image 67
Fred Foo Avatar answered Mar 13 '26 23:03

Fred Foo


The first is an ordinary, fully contiguous array, the second is also known as jagged array or lliffe vector and can e.g. be used to represent triangular structures.

like image 45
Sebastian Mach Avatar answered Mar 13 '26 22:03

Sebastian Mach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!