say i have a 2D array
Code:int arr[5][2] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,10} }; now if i say arr[0].. its internally treated as *(arr+0) i.e. the address of 0th 1D array . but what if i say (arr+0) (arr+1) (arr+2) i.e without *
say i have a 2D array
Code:int arr[5][2] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,10} }; now if i say arr[0].. its internally treated as *(arr+0) i.e. the address of 0th 1D array . but what if i say (arr+0) (arr+1) (arr+2) i.e without *
Then it returns the address, not the value.
but even *(arr+0) returns the address of 0th 1 D array then how is it different from (arr+0) which according to you returns the address of 0th 1D array again as well ?? :O
so in 2D array is (arr+0) and *(arr+0) same ??
This part has an error:
Because *(arr+0) is the VALUE of the first element of the arr[] array, it is not the address. An example:now if i say arr[0].. its internally treated as *(arr+0)
i.e. the address of 0th 1D array .
but what if i say
(arr+0)
(arr+1)
(arr+2)
i.e without *
Output is 4.Code:#include <stdio.h> int main(void) { int i, n; int a[]={0,1,2,3,4,5,6,7,8,9}; printf("%d\n",*(a+4)); return 0; }
If you remove the * from the above, you should get this warning from your compiler:
warning #2234: Argument 2 to 'printf' does not match the format string; expected 'int' but found 'int *'.
And if you mistakenly run it, you get a value unrelated to the value in the array.
Are you trying to print addresses for the array, instead of values?
No! With the *, you are dereferencing the pointer, and you have the value the pointer is pointing at.
Without it, you are referring to the value of the pointer itself - and it will always have an address, not an array value.
Last edited by Adak; 01-09-2012 at 02:32 AM.
In short yes.
In a 2D array, the first element's address is also the first address of the first array (say array [5] although you can't write it this way in a program).
So array [5] has elements of 2 * sizeof(int) and will advance that way with any addition, so it points to the next row of 2 elements.
At first in learning it, I was confused because I thought *x could be called "That which x points to", and in that case it is.
But when it comes to a multi dimension array, *(arr +0) is still "That which arr+0 points to", but what it points to is another pointer.
Therefore you have a pointer to a pointer in 2D arrays. in 3D arrays you have a pointer to a pointer to a pointer.