c++ and poiters to arrays

eliot's Avatar, Join Date: Aug 2010
Newbie Member
HI;
could anyone tell me how to use a pointer for multidimensional arrays.

i only know about using pointers for one dimensional arrays.

and especially if the base type of pointer and array is char.that means dealing with aggregate items in two dimensions.

in memory multidimensional arrays are made of sets of one dimensional arrays.

i would be most thankful...
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
If you already know how to use 1D arrays, 2D and higher are easy. A 2D array is basically a one-dimensional array of pointers to one-dimensional arrays. A 3D array is a 1D array of pointers to 2D arrays and so on.

In fact if you can already handle an array of chars, that's already 2D array handling.
Code:
char *my2Darr[10];
is a 1D array of pointers to char; let's create the memory:
Code:
for (int i=0; i<10; i++) my2Darr=malloc(10);
so now we have a 10x10 array of char. Let's copy some text to one of the strings:
Code:
strcpy(my2Darr[5],"Hello");
Defining a 2D array is simple enough:
Code:
int matrix[10][20];
defines 10 arrays of 20 elements each (which to my mind is the wrong way round, if you define something[10] that should give you an array of 10 somethings, so if something itself is an array, e.g. stelse[4], then stelse[4][10] should be an array of 10 stelse[4]s, but it's actually 4 stelse[10]s.)

You could always define a block of memory as 1D, then use x+width*y semantics to get at the element you want, e.g
Code:
int matrix[200];
matrix[5+20*6]=7;
which is effectively what the compiler does for you anyway.
shabbir like this
LordN3mrod's Avatar, Join Date: Sep 2010
Go4Expert Member
First of all, it is essential to understand that an array is NOT a pointer
int a[10]
the type of a is NOT int*, it is int[10]
However, an array type can be implicitly converted to a pointer type.
If you declare a function taking an array, it is equivalent of declaring an array taking a pointer.

void f (int a[19] )
is same as
void f (int a[24] )
void f (int a[] )
void f (int* a )

a two-dimensional array is an array of arrays, that is
float a[3][4] is an array of 3 arrays of 4 floats.
like in the case of one-dimensional arrays, this one can also be implicitly converted to a pointer - a pointer to an array of 4 floats, but NOT to a pointer to pointer to float.

Thus,
void f(int a[10][20])
is equivalent to
void f(int a[][20])
is equivalent to
void f(int a[15][20])
is equivalent to
void f(int (*a)[20])
but is NOT equivalent to
void f(int**)

the second dimension HAS to be provided

Hope this helped
shabbir like this