Shweta
Shweta

Reputation: 5456

2d array representation through pointer

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);

Upvotes: 2

Views: 6168

Answers (5)

John Bode
John Bode

Reputation: 123468

Apply the rule recursively:

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

Upvotes: 2

AnthonyLambert
AnthonyLambert

Reputation: 8830

// 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....

Upvotes: 0

pmg
pmg

Reputation: 108988

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`

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

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

*(*(a+i)+j)

Upvotes: 4

user23743
user23743

Reputation:

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).

Upvotes: 0

Related Questions