home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!microsoft!wingnut!pauljo
- From: pauljo@microsoft.com (Paul Johns)
- Subject: Re: Passing 2-d arrys to functions
- Message-ID: <1993Jan11.235754.23011@microsoft.com>
- Date: 11 Jan 93 23:57:54 GMT
- Organization: Microsoft Corp., Redmond, Washington, USA
- References: <1993Jan11.030238.6688@nuscc.nus.sg> <24568@alice.att.com> <726521188snx@trmphrst.demon.co.uk> <RUNE.93Jan10125255@pandora.nta.no>
- Distribution: usa
- Lines: 57
-
- In article <1993Jan11.030238.6688@nuscc.nus.sg> suresh@argon.iss.nus.sg wrote:
-
- > Yes, I think this program will work always .. since you have passed in
- > a double ** pointer which is a vector of double*, the least dimension
- > of the array is not required to correctly index the values.
- > Although the same syntax can be used to access 2-d arrays (no flames
- > please .. I mean statically allocated as in double arr[2][2] ) and
- > variables of type pointer to pointer ( double **), the underlying memory
- > layout need not be the same. However, the algorithm used to index either
- > one is the same.. pointer arithmetic.
-
- The algorithm is different. Check out the assembly code generated to
- see how.
-
- > I believe( correct me if I am wrong) most or all C/C++ compilers always
- > use the same pointer arithmetic no matter whether the array passed
- > is declared as double arr[][least_dim] or double **.
-
- This is absolutely not true. The two pointers are of different types.
- The type for the array case is "double (*arr)[least_dim];". The type
- in the pointer case is "double **arr;". The addressing they use isn't
- the same. (Show the result of arr++ in the two cases, or the type
- of *arr--to see this.)
-
- To do "arr[3][4]" you need to do entirely different operations depending
- on the type of arr:
-
- In the array case, you multiply the column number (3) by the row size
- (least_dim) and add the row number (4), finally multiplying by the
- element size (8) to find the offset of the element from the beginning
- of the two-dimensional array's block of contiguous memory.
-
- In the pointer case, you index into the pointer array (using 3),
- then use the address found there to index (using 4) into the one-
- dimensional array of doubles pointed to by the pointer in the
- pointer array.
-
- > This explains
- > how we can successfully mix pointer arithmetic and array-indexing.
- > The last dimension is required merely for setting up storage.
-
- No. This explains why you can't mix pointer operations. Many have
- tried, and many have failed.
-
- It **IS** ok to mix []'s and pointer arithmetic **IFF** the underlying
- pointer types are the same:
-
- Array type Underlying pointer type
-
- char a[3]; char *a;
- char a[3][5]; char (*a)[5];
- char *a[4]; char **a;
-
- The rule is to drop the leftmost subscript and bind the * operator
- tightly to the identifier.
-
- // Paul
-