Uhrbaan
Uhrbaan

Reputation: 31

incrementing a pointer inside a function

I was writing a program in C just for fun (and exercise) and I stumbled upon this behavior which I don't understand... Incrementing a pointer within a function is not possible with the ++ operator

void fn(void **p)
{
    *p++;
    // other options like *p+=1 or ++*p work, but I dont understand why...
}

Could someone explain (for a noob ;) ) why this doesn't work ? I am very curious.

Upvotes: 1

Views: 298

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

It seems you are passing a pointer to the function indirectly through a pointer to it.

So to increment the original pointer you need to dereference the pointer that points to the original pointer and then increment it.

For example

++*p;

Otherwise this expression statement

*p++;

does not increment the original pointer because the statement is equivalent to

*( p++ );

due to the operator precedences.

In fact the above statement is equivalent to

p++;

because the result of the operator * is not used.

On the other hand, even if you will write the statement correctly (according to the logic)

++*p;

it does not make a sense because you may not increment a pointer of the type void * (though some compilers for the backward compatibility allow such an operation with pointers of the type void * similarly to pointers of the type char *) because the type void is an incomplete type and can not be completed.

Upvotes: 1

Related Questions