The reason this works is because you are increasing your pointer by pointing to new spots in memory (which your program may or may not be allocated for use). I assume that you are declaring this on the stack, and so the undefined behavior looks “normal”.
I don’t think you understand the power of the pointer and the syntax you used. Note that the following is equivalent:
int arr[ 2 ] = { 1, 2 }; int *pi = &arr; // The following output is equivalent to... for ( int i = 0; i < 2; i++ ) { printf( "arr[i] = %d.\n", arr[ i ] ); } // this. for ( int i = 0; i < 2; i++ ) { printf( "*(p + i) = %d.\n", *( p + i ) ); }
Consider this alternative implementation of your code to emphasize how you point to new memory addresses by indexing elements outside your array.
int *d = ( int * )malloc( 2 * sizeof( int ) ); *( d + 0 ) = 4;
Just write down your code quickly. Usually malloc follows free - so use it appropriately so that there are no memory leaks.
Hope this helps! Feel free to correct me if I made a mistake.
source share