Trouble understanding pointers.

Programming, for all ages and all languages.
Zekrazey1
Member
Member
Posts: 37
Joined: Sat Mar 10, 2007 8:28 am

Post 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.
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Post by Candy »

jnc100 wrote:I must agree with Candy here. If you create an array such as

Code: Select all

int arr[4][4]
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

Code: Select all

int **arr
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.
User avatar
JamesM
Member
Member
Posts: 2935
Joined: Tue Jul 10, 2007 5:27 am
Location: York, United Kingdom
Contact:

Post 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.
Post Reply