Oct 23, 2012 at 3:07am UTC
Which is the correct way to create a Dynamic 2-Dimensional array?
1 2 3 4 5 6 7 8
int **2d()
{
int **array= new int *[10];
array[0]=new int [100];
for (int i=0; i<10; i++)
array[i]=array[0]+10*4*i;
return array;
}
or..
1 2 3 4 5 6 7 8
int **2d()
{
int **array= new int *[10];
array[0]=new int [100];
for (int i=0; i<10; i++)
array[i]=array[0]+10*4*i; //since (int) is 4 bytes across
return array;
}
I have no idea how to test the above arrays to see which one is correct.
I figure the above code is more efficient then
1 2 3 4 5 6 7 8 9
int **2d()
{
int **array= new int *[10];
array[0]=new int [100];
for (int i=0; i<10; i++)
array[i]=array[0]+10*4*i;
return array;
}
as, this code calls the "new" more then once.
Edit: Sorry, I was not clear on the fact that this is a dynamic 2D array.
Last edited on Oct 23, 2012 at 3:51pm UTC
Oct 23, 2012 at 4:58am UTC
I'm a beginner as well, sorry if this isn't much help, but unless I misunderstood, a 2D array can be made just like this:
int BigArray[8][8];
You don't need to call new if you just want to have a 2D array. That would give you a 2D array of ints with 8 rows and 8 columns. Really, in memory, it's the exact same thing as writing:
int BigArray[64];
because it's all contiguous anyway, but dividing them into cols and rows feels more logical for accessing correct indices.
Last edited on Oct 23, 2012 at 4:58am UTC
Oct 23, 2012 at 3:54pm UTC
sorry, I wasn't clear on the fact that this has to be a dynamic 2D array and not a static one.
This is the line that divides the array into 10x10 columns and rows.
1 2
for (int i=0; i<10; i++)
array[i]=array[0]+10*4*i;
my problem was whether or not the above code or the below code is right to divide the 100 dynamic memory into a [10][10] array.
1 2
for (int i=0; i<10; i++)
array[i]=array[0]+10*i;
since each int holds 4 bytes i would think that the pointers are incremented by 4 each time... but i have no idea how to check if it actually is...
Last edited on Oct 23, 2012 at 11:25pm UTC
Oct 23, 2012 at 11:25pm UTC
bump, this fell to 3rd page... and i still want answer
Last edited on Oct 23, 2012 at 11:25pm UTC