开发者

2d array representation through pointer

开发者 https://www.devze.com 2023-01-17 13:42 出处:网络
Addresses of 1d arrays are actually taken as a[i]=*(a+i); Are the addresses of 2d arrays calculated as a[i][j]=**(a+i开发者_运维百科+j);

Addresses of 1d arrays are actually taken as

a[i]=*(a+i);

Are the addresses of 2d arrays calculated as

a[i][j]=**(a+i开发者_运维百科+j);


The other answers are not quite correct. It's more like:

*(*(a+i)+j)


Apply the rule recursively:

a[i][j] == *(a[i] + j) == *(*(a + i) + j)


No, because then a[1][2] and a[2][1] would be at the same place. Something like *(a+i*n+j) for an n-by-m array is closer to the mark (though beware I type the exact expression into a markdown editor, not a unit test).


No. a and a[i] are of different types (respectively int** and int*).

Supposing that in your example a was defined as array of array of int (eg a[10][20]), when you pass it to a function (thereby converting it to pointer to the first element of the array) you have (with further "simplifications" for the 2nd array rank)

    a           is of type `int**`
    a[i]        is of type `int*`
    a[i][j]     is of type `int`

    *(a+i)      is of type `int*`
    a+i+j       is of type `int**`
    *(a+i+j)    is of type `int*`
    *(*(a+i)+j) is of type `int`


// CTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

void print (int i, int j )
{
    int a[3][3] = {
        { 1,2,3 },
        { 4,5,6 },
        { 7,8,9 }
        };
    printf ("%d\n", *(*(a+i)+j) );
    printf ("%d\n", a[i][j] );
}

int _tmain(int argc, _TCHAR* argv[])
{

    print (0,0);
    print (1,1);
    print (2,2);
    return 0;
}

Returns:

1 1 5 5 9 9

*This has been run through a compiler....

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号