Pointers problem
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 happe开发者_JAVA技巧ning.....
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.
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++;
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.
精彩评论