Friday, October 21, 2005

Re: clear the concept of 2D array and pointers


Your concern is right!
The question you are asking here is quite subtle.
Apart from the address of elements you have to pay attention at the
type of the element.
See,
when you have an "int s[10]"
s gives you a value which is an address of first element of the
array. (This is called "decay")
The TYPE of this value is " int * ". Which means a pointer to an
integer.
&s[0] also gives you a value which is an address of the first element
of the array but there is no decay here. The TYPE of this value is "
int * ". Which means a pointer to an integer.
Real interesting part starts here:
&s is different thing all together as far as the TYPE is concerned. The
value given by &s is same as s or &s[0] but the TYPE of &s is " int
(*)[10] ". Note the difference. It says it is a pointer to an array of
10 integers. This is definitely not the same as pointer to an integer.
The concept of "decay of array name to the pointer to the first
element" in C really blurs this distinction!

Now apply this concept to 2D arrays.
int s[5][2]
You understand s[0][0] and &s[0][0].
Now s[0] is an array of integers. so s[0] DECAYS to "int *" A pointer
to the first element of s[0] which is infact &s[0][0] by value. But
&s[0] is not the same (though the address is same) The TYPE of &s[0] is
" int (*)[2] " which means a pointer to an array of 2 integers. Now
imagine what s is : It is, after decay, int (*)[2]. and &s is int
(*)[5][2]. Note the difference. First is a pointer to an array of 2
integers. Second one is a pointer to a 2 dimentional array of integers.
Also note that decay happens only once for the last dimention of the
array.
So for s[5][2][3]
s means int (*)[5][2]
and
&s means int (*)[5][2][3]
I know this is getting very involved! Play with a c++ compiler instead
of C compiler which spits out " type errors". such as int *p = &s; C
compiler won't. Last note: CONCENTRATE ON TYPE NOT THE VALUE. Hope that
helps.

0 Comments:

Post a Comment

<< Home