Wednesday, June 27, 2007

Multi dimensional arrays and pointers to pointers

C does not really support Multi dimensional arrys.what we code as Multi dimensional arrays are arrays of arrays.Simple to tell but thers more to it

int x[5][6]; //this is an 5 array of 6 element array each
int *x[6]; //this is a pointer to the 6 element array

Both are pointers here.x at both places points to x[0][0].x[2][3] at both places mean the same.But the difference is that the first assignment allocates memory for 5*6 30 integer elements in a contuguous manner..But the second assignment as we know just creates a pointer that ponts to nothing.It has to later point to something else and as already stated the pointer x in first is static and thee later pointer is not it can point to any memory location later provided that is also an integer array


Now more in to the depth

int cal[12][31]; //suppose a declaration and values have been assigned
int (*month)[31]; // month is a pointer to a 31 element integer array...fine??

now we can say

month = cal; // here month points to the first month out of the 12 months.diagramatically its like this.asume that there are 12 boxes each of lenth 31
cal points to the first box always.this is fixed since its an array and its static.

month also points to the same box now

cal+1 , cal+2 , manoth+1 and month +2 etc will point o subsequent boxes

cal[1] and cal[2] what about these..lets aply same rule...cal[2] = *(cal + 2) as said

so cal[2] will point to the first element in the thirs box....simple..since here as already said * operator will dereference the object that we point to.....

so cal[4][7] = *(cal[4] + 7) = *(*(cal + 4) + 7)

we get this by applying the referencing operators repeatedly

Some dereferencong now.......

&cal[5] //this points to as we know the 6th Box.since cal[5] points to the first element of 6th box and the & operator will get the address of that box

&(*month)[31] // Month is a pointer to an integer array that is a box...so *month will point to the firts element of that array...(*month)[31] is the value of the last element as array subscript points to the value......

&(*month)[31] gets the pointer to the last element of the month array box ultimately

Thanks,
Prasanna

No comments: