A few tips :
You should try this experiment again but this time make a an array and while you're at it, give it values :
int a[ 5 ] = { 0, 1, 2, 3, 4 };
You can also move the pointer. This statement is valid :
++p;
Try it and see the results.
--p;
is also valid, but will point to invalid memory if
p
equals the address of
a[0]
.
I prefer to see addresses in hex so I use a statement like this to display them :
printf( "p=%08X\n", p );
So, combining all this together and making a function out of it can result in this code :
void displayPointer( int * p, int a[] )
{
printf( " p=%08X, value is %d\n", p, * p );
printf( "p+1=%08X, value is %d\n", p+1, *(p+1) );
printf( "incrementing pointer\n" );
++p;
printf( " p=%08X, value is %d\n", p, * p );
printf( "decrementing pointer\n" );
--p;
printf( " p=%08X, value is %d\n", p, * p );
}
int main()
{
int a[ 5 ] = { 0, 1, 2, 3, 4 };
int * p;
p = & a[ 0 ];
printf( "p is address of a[ 0 ] :\n" );
displayPointer( p, a );
p = & a[ 2 ];
printf( "p is address of a[ 2 ] :\n" );
displayPointer( p, a );
return 0;
}
Try running this and observe the results.