Alex Rivera | Logout

How to post-modify a C pointer?

Asked 2012-06-26T10:29:52.593
9

In modern processors it is possible to load a register from memory and then post-modify the indexing pointer by a desired value. For example, in our embedded processor, this will be done by:

ldr r0, [r1], +12

which means - load the value pointed to by r1 into r0 and then increment r1 by 12:

r0 = [r1]
r1 = r1 + 12

In the C language, using pointer arithmetics, one can assign a value using a pointer and then advance the pointer by 1:

char i, *p, a[3]={10, 20, 30};

p = &(a[0]);
i = *p++;
// now i==10 and p==&(a[1]).

I am looking for a way to dereference a pointer while post-modifying it by an offset other than 1. Is this possible in C, so it maps nicely to the similar asm instruction?

Note that:

i = *p+=2;

increases the value in a[0] w/o modifying the pointer, and:

i = *(p+=2);

pre-modifies the pointer, so in this case i==30.

Edit
Report

1 Answer

3

You can do it this way, but don't do it:

i = *((p += 2) - 2);

(not exactly post-modify)

answered 2012-06-26T10:56:20.743

Your Answer