tonyjosi
tonyjosi

Reputation: 845

How to use address-of operator along with prefix increment on pointers in the same statement?

Is it possible to use address-of operator alongside prefix increment on pointers in the same statement, if yes how?

Example,

#include <stdio.h>
#include <stdint.h>

void main() {
    uint8_t arr_var[2];
    arr_var[0] = 0xa;
    arr_var[1] = 0xf;
    uint8_t *ptr = arr_var;
    uint8_t **dptr = &(++ptr);
}

Im getting the error

error: lvalue required as unary '&' operand

uint8_t **dptr = &(++ptr);

Is there any other alternatives rather than making it 2 separate statements (increment (ptr++) and then address-of (&ptr)).

Upvotes: 0

Views: 253

Answers (2)

Ardent Coder
Ardent Coder

Reputation: 3995

Problem:

Unlike C++, pointer incrementation/decrementation does not return an lvalue in C.

The addressof operator must have an lvalue as the operand.

Solution:

Since you want to achieve your task in a single statement, here is a tricky way to do it:

uint8_t **dptr = ++ptr ? &ptr : &ptr;

Some other solutions from the comment section:-

Lundin: uint8_t **dptr = (++ptr, &ptr);

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409442

It seems I was thrown off by one difference between C and C++...

In C the result of the increment or decerement operators is never an lvalue, and you can only get the addresses of lvalues.

This increment/decrement reference explicitly include the example &++a and says it's invalid.

To get a pointer to ptr you must use plain &ptr. Before of after incrementing the pointer doesn't matter, as dptr will be a pointer to ptr itself.

Upvotes: 2

Related Questions