tags:

views:

97

answers:

5

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

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

Graham Lee
A: 
// 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....

Tony Lambert
I am sorry but its not working
Shweta
This is supposed to work. What exactly doesn't work?
codymanix
@codymanix: There is no double dereferencing, so the type of all that is pointer-to-int.
Oli Charlesworth
This definitely works now I tried it...
Tony Lambert
+2  A: 

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

*(*(a+i)+j)
Oli Charlesworth
thanks very much it helped me but its*(*(a+i)+j)
Shweta
@Shweta: answer edited accordingly
Oli Charlesworth
A: 

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`
pmg
If `a` is indeed a "2d array" (by which we normally mean an array of arrays) then it decays to type `int (*)[n]`.
caf
Yes, that's why I wrote "further simplification for the 2nd rank". Thank you for making it clearer.
pmg
It clarified my concepts. So thanks for help
Shweta
It's not right though - if `a` is defined as `a[10][20]` then `a` is **not** of type `int**`, it's of type `int(*)[20]`.
caf
A: 

Apply the rule recursively:

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