I've got array: int i[20][30]
. What is the fastest way to make int**
pointer to use on it?
My friend just wrote function which uses same size arrays and my function is on pointers and I need to pass his data.
I've got array: int i[20][30]
. What is the fastest way to make int**
pointer to use on it?
My friend just wrote function which uses same size arrays and my function is on pointers and I need to pass his data.
int a[20][30]; // data as 2D array
int *ap[20]; // array of pointers
for (j = 0; j < 20; ++j)
ap[j] = a[j]; // convert array to pointers
// can now pass `ap` to function expecting `int **`...
You can't have an int **
pointer to that array directly, it wouldn't make any sense. If you want to access the array as a block of memory you can just use:
int *p = (int *)i; // you can go to up (p + 20*30)
Otherwise you need a pointer to an array of int[30]
, i.e.
int (*p)[30] = &i[0]; // points to first row
With the first one, because of the cast, you can then define:
int **p2 = &p;
And you can access the array with *(*p2 + n)
. You've cast away the array dimensions, but as long as you use them in the pointer calculations, it's all valid, i.e. *(*p2 + 35)
refers to row 2, column 6 (one row of 30, plus element 5 of the next). This is very quick, but if the function needs to operate on the array using the original dimensions, this wouldn't work (since it isn't an array of pointers).
you cant change int i[20][30]
to int **
except of manually go over the data and build it.
but, something that may help you, every xD array in c++ is just a 1D array with a somehow complexed way to access a member.
Example:
#define MaxX 20
#define MaxY 30
int i[MaxX][MaxY];
...
//When you write:
i[x][y] = something;
//It's actually been translate to:
i[x * MaxY + y] = something;