Page 2 of 2
Posted: Sat Aug 18, 2007 11:04 pm
by Zekrazey1
In general, pointers are not arrays. Their representation just happens to degenerate to the same type in the case of a one dimensional array. Similarly, in general array[16] isn't the same as array[4][4], even if they happen to look the same in memory.
That doesn't mean you can't make use of the knowledge of what choices a c compiler will make if those choices are specified beforehand.
Posted: Sun Aug 19, 2007 11:42 am
by Candy
jnc100 wrote:I must agree with Candy here. If you create an array such as
then by accessing arr by itself you do not get a pointer to int[4] but rather get &arr[0][0]. i.e. the compiler creates an array of size 16 * sizeof(int) and then calculates offsets into it from an expression of the form int[x][y] given that it knows the maximum size of each dimension (it only really needs to know one). A search can verify that, given the definition above, arr[16] == arr[4][4]
If, on the other hand, you define a type as
then arr is a pointer to the start of an array of int * which is of unknown size. Therefore, if you try and access arr[4][4] from there you will get the fourth element of the array of int* and then get the fourth element of the array which that points to. You may well get a compiler warning, however.
Fifth element, actually. You count from 0.
Passing a type of int[4][4] to a function expecting int ** would not produce the expected result, because the receiving function has no idea as to the dimensions of the original array.
It would assume the result of indexing the pointer at the 5th location would result in a pointer, whereas the entry would actually contain a integer that is part of the array.
Posted: Mon Aug 20, 2007 3:43 am
by JamesM
it is a poor assumption on the part of the programmer to think that an int a[4][4] is not equivalent to a pointer to pointer to an int.
but it
isn't! They
aren't equivalent! I think that point has been quite well made so far.