c++ and poiters to arrays

Discussion in 'C++' started by eliot, Aug 24, 2010.

1. eliotNew Member

Joined:
Aug 24, 2010
Messages:
1
0
Trophy Points:
0
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...

2. xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
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;

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,"Hello");

Defining a 2D array is simple enough:
Code:
int matrix;

defines 10 arrays of 20 elements each (which to my mind is the wrong way round, if you define something that should give you an array of 10 somethings, so if something itself is an array, e.g. stelse, then stelse should be an array of 10 stelses, but it's actually 4 stelses.)

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;
matrix[5+20*6]=7;

which is effectively what the compiler does for you anyway.

shabbir likes this.
3. LordN3mrodNew Member

Joined:
Sep 4, 2010
Messages:
22
11
Trophy Points:
0
Occupation:
Software Developer
Location:
Yerevan, Armenia
First of all, it is essential to understand that an array is NOT a pointer
int a
the type of a is NOT int*, it is int
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 )
is same as
void f (int a )
void f (int a[] )
void f (int* a )

a two-dimensional array is an array of arrays, that is
float a 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)
is equivalent to
void f(int a[])
is equivalent to
void f(int a)
is equivalent to
void f(int (*a))
but is NOT equivalent to
void f(int**)

the second dimension HAS to be provided

Hope this helped

shabbir likes this.