DEV Community

Srijeyanthan
Srijeyanthan

Posted on

1 1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay