DEV Community

Srijeyanthan
Srijeyanthan

Posted on

Decode pointer arithmetic

This is a very short article about quick pointer arithmetic decoding. The basic pointer arithmetic is very easy to handle, and most of us are familiar with them. Array arithmetic is a bit tricky, but using following formula in your mind, can be easily interpreted.

in C/C++ handle pointer with an array as follows

int a[5] = {1,2,3,4,5}

int *p = a

print a // address of a, in this case, &a[0]
print a+1 // address of a[1] -> &a[1]

print *a // dereference array a[0]
print *(a+1) // dereference array a[1]

print p // address of &a[0]
print p+1 // address of &a[1]
print *(p+1) // dereference array a[1]

Look at the following example

int(*a)[5]; 

int b[5] = { 1, 2, 3, 4, 5 }; 
int i = 0; 
// Points to the whole array b 
a = &b; 

If we print the value of *(*a+1)? Can you guess?

Now the question of, do we have any fundamental formula to apply all the cases, yes !!, we do have.

*(A+1) = A[i]
A+1 = &A[i]

Now, let's decode the above expression, *(*a+1) -> *( *(a+0) +1) -> *(A[0] +1) -> *(A[1])

int B[2][3]

print B = &B[0] Using above formula, B+0 -> &B[0]
print *B = B[0] or &B[0][0] *B -> *(B+0) -> B[0]
print B+1 = &B1 -> &B[1]
print *(B+1) = B[1] & &B[1][0] *(B+1) -> B[1]

print (B+1)+2 B[1]+2 &B[1][2] *(B+1)+2 ->B[1]+2 -> &B[1][2]
print *(*B+1) = = *(&B[0][1]) *(
(B+0)+1) -> (B[0] +1) ->(&B[0][1]) -> B[0][1]

Likewise, all the complex pointer arithmetics are easily solvable, There are many use cases for this variation, developers should remember this variation as functions are accepting all this variation to access. It will help to read complex source codes.

Top comments (0)