[try Beta version]
Not logged in

 
Dynamic 2 Dimensional Array

Oct 24, 2012 at 10:12am
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 know that it is possible declare a 2D array like this...
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;

}

however, i also know that calling "new" once for a chunk of memory is more efficient then calling new multiple times for small pieces of an array. I want to the code that is more efficient...
Last edited on Oct 24, 2012 at 10:13am
Oct 24, 2012 at 10:36am
I do not see any difference between these three code snips.
Using such method of allocating an array you should not forget that you cannot delete [] a[i] except only when i = 0 that is when a[0] is used.
Oct 24, 2012 at 3:18pm
There really is no difference.
However, I haven't done pointer arithmetics in a while, but from what I remember from it, the '4' might be unnecessary and may cause errors. That is because the compiler 'knows' array[0] is a pointer to int, so it will increment by 'sizeof int' steps.
Oct 24, 2012 at 3:30pm
from what I remember from it, the '4' might be unnecessary and may cause errors


This is correct. You must not multiply by 4. Pointer math is not done in bytes, it is done in 'elements' (ie: the compiler already multiplies by sizeof(int) for you)
Topic archived. No new replies allowed.