Tuesday, February 19, 2013

pointer arithmetic


bool maze[3][5];
for(int i=0;i<3;i++)
{
bool (*row)[5]=maze+i;
for(int j=0;j<5;j++)
(*row)[j]=true;
}

_____________________________________________________________________________

1. arbitrary pointer casting

Here's an example:

// casting 32 bit int, 0x0000ffff, to a pointer

char *ptr = reinterpret_cast<char*>(0x0000ffff);

2. arrays and pointer arithmetic

int arr[10];

arr[i]==*(arr+i)

Formular: addr( ptr + i ) = addr( ptr ) + [ sizeof( T ) * i ]

Example:

int * arr[ 10 ] ;
   int ** ptr = arr ;

addr( ptr + i ) = addr( ptr ) + [ sizeof( int * ) * i ]
                   = addr( ptr ) + [ 4 * i ]



Parameter Passing an Array:

If you pass an array to a function, it's type changes.
   void foo( int arr[ 10 ], int size ) {
     // code here
   }
The compiler translates arrays in a parameter list to:
   void foo( int * arr, int size ) {
     // code here
   }

it will not cause problem because the parameter is passed by value.

Passing the array size

   // Compiler translates arr's type to int * 
    void foo ( int arr[], int size ) {
       // Prints 4 
       cout << sizeof( arr ) ;

       int arr2[ 10 ] ;

       // Prints 40 
       cout << sizeof( arr2 ) ;
    }

Two dimensional array

int arr[10][12];

the type is not int**

arr[0]=&arr[0][0];
arr[1]=&arr[1][0];
arr[i]=&arr[i][0];

(different from int**!)
lesson: a two-dimensional array is not the same as an array of pointers to 1D arrays.

The actual type for a two-dimensional array, is declared as:

int (*ptr)[10];

which is a pointer to an array of 10 elements.

addr( & arr[ row ][ col ] ) = addr( arr ) + [ sizeof( int ) * COLS * row ]
                                             + [ sizeof( int ) * col ]

When you have a 2D array as a parameter to a function, there's no need to specify the number of rows. You just need to specify the number of columns. The reason is the formula above. The compiler can compute the address of an element in a 2D array just knowing the number of columns.

Note that int **arr is an array of pointers (possibly to 1D arrays), while int arr[][ COLS ] is a 2D array. They are not the same type, and are not interchangeable.




No comments:

Post a Comment