tags:

views:

107

answers:

3

What is the difference b/w

struct {
    float *p; 
}*ptr=s;

*ptr->p++

and

(*ptr->p)++;

I understand that the former points to the next address while the latter increments the value by 1 but I cannot get how it is happening.....

+7  A: 

It's all about precedence.

In the first example you are incrementing the location that *p points to.

In the second example you are dereferencing *p and incrementing the value.

Quintin Robinson
Hey! I saw that! :P
Artelius
I have a tendency to modify my answer slightly for word correction after I post it initially, sorry if it looked a little odd.
Quintin Robinson
Don't worry, I do the same. Unless you're one of the first few answers to a question, it's hard to get the upvotes you deserve.
Artelius
@Artelius: I know what you mean. So let's all try to upvote all good answers, not just the good answers that arrive quickly. (I won't put an answer, since that would be blatant reputation-whoring)
David Oneill
If indirection is applied on p (that is *p) then it will not be pointing to a location. It will be a value. You have mentioned "location that *p points to.", Please check.
Ganesh Gopalasubramanian
+2  A: 

Due to C operator precedence,

*ptr->p++;

is equivalent to

*(ptr->p++);

so it actually increments the pointer, but dereferences the original address, due to the way postfix ++ works.

However, since nothing is done to the dereferenced address, the statement is equivalent to

ptr->p++;
Artelius
+1  A: 

It might be better to write it as follows:

struct S
{
    float p;
};

S* ptr;

This way you have a named struct containing a float. It is named S. You then declare an S pointer called ptr.

 1) ptr++;
 2) ptr->p++;
 3) (ptr->p)++;
 4) (ptr++)->p++;

in 1) you increment the pointer by sizeof( S ).
in 2) you increment the float in the struct.
in 3) you increment the float in the struct.
in 4) you increment the pointer by sizeof( S ) and then increment the float in the struct.

Goz
In C, the struct tag does not define a new type. You need to `typedef` or use the whole name `struct S` when declaring variables of the struct type.
pmg
Oh ... I thought that was no longer the case ...
Goz