int f(int b[][3]);
int main()
{
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
f(a);
printf("%d\n", a[2][1]);
}
int f(int b[][3])
{
++b;
b[1][1] = 1;
}
3x3 => 9 elements contained in the 2-D array a. When it's passed, then b will contain the the base address of the a. If suppose base address is 1000 then ++b how does it 开发者_开发技巧to 3 locations and not 9 locations ahead? Are we doing typecasting when the variable a is passed to b[][3] as only the three elements?
How does b[1][1] correspond to the address of 8 and not 5?
We can't do incrementing or decrementing in an array as array is a const pointer, but how is that they are incrementing ++b as its an array?
The function heading
int f(int b[][3])
is a nothing more than a confusing way to write (and is exactly equivalent to)
int f(int (*b)[3])
The type of b is "pointer to three-element array of int". When you increment the b parameter you adjust it to point to the next three-element array of int -- now it points to {4,5,6}. Then b[1] indexes once more and gives you the array {7,8,9} and finally b[1][1] gives you the oneth element of that array, namely 8.
C multidimensional arrays are really linear, except that there is syntactic sugar to do the arithmetic correctly.
so with b[][3], it excepts a 1-D array and implicitly translates b[i][j] --> b[3*i+j]
++b works as follows: (++b)[i][j] = ORIGINAL_b[i+1][j]. So in your case, you are accessing ORIGINAL_b[1+1][1] = ORIGINAL_b[2*3+1] = ORIGINAL_b[7] (the 8th element)
Note: this is in stark contrast to the dynamic malloc version (in **b, b is a array of pointers)
How is b[1][1] corresponds to the address of 8 and not address of 5?
This is expected behavior:
int f(int b[][3])
{
//at this point b[0][0] is 1, b[1][1] is 5
++b;
//now b[0][0] is 4, b[1][1] is 8
b[1][1]=1;
}
The pointer has incremented to point to the next memory slot, which is the second slot of array a. Basically:
b -> a[0]
++b -> a[1]
加载中,请稍侯......
精彩评论