What is the difference between *p and p*?
开发者_开发技巧Is p*
another way of using pointers?
Is *p
, a pointer variable, different from p*
?
*p
is dereferencing a pointer, p*
is multiplying the pointer by something.
The syntax
*ptr
Means to dereference the pointer to get the object it points at.
The syntax
ptr*
Is not meaningful in C, unless it's the start of a multiplication. For example:
*ptr*137;
Means "dereference ptr, then multiply the value it points at by 137.". Outside of this context, though, putting a star after a pointer variable is illegal.
Now, what is legal is putting a star after a type, as in
int*
Which describes a type that's a pointer to the type to the left of the star. Interestingly, this means that you can't put a star before a type (that's not legal) nor a star after a pointer (since the dereference operator goes to the left). The reason is partly due to the idea that in C, types should mimic how they work. That is, if you have
int *p;
Then the syntax is a visual cue that to get to the integer pointed at by p, you should put a star in front of it.
Prefix vs binary vs type expressions
The * is a prefix unary operator for pointers and an infix unary operator for multiplication. There is a special case where a pure type is all that is needed so one will see things like sizeof(int *)
, or void f(int *, char *)
, but it's still a prefix *
on an unnamed identifier.
Postfix dereference in an alternate universe
It's interesting to note that *
could have been a postfix unary operator and in that case a few things in the language might have worked out slightly better. For one, the ->
operator would not have been necessary:
p->field
p*.field // like Pascal's p^.field
Even today, you can use:
p[0].field
Also...
(*x)->y // today
x**.y // alternate universe
*x->y // today
x*.y* // alternate universe
DMR appeared to state1 in one paper that he would have switched to postfix dereference early on but C was already too well established. The expression syntax is reasonably workable either way but it would also have untangled the C declaration syntax and removed most of the need to read them in an inside-out way that people consistently have trouble with:
int *fp();
int fp()*; // alternate universe
int (*pf)();
int pf*(); // alternate universe
int *(*pfp)();
int pfp*()*; // alternate universe
1. See The Development of the C Language., Dennis M. Ritchie
I guess you already know this is a multiply operation:
p * 3;
The other case:
Retrieve the value from where 'p' points to:
int i = 1;
int *p; // Declare p as an int * (pointer to an int)
p = &i; // Set the address p points to
printf("The value of p is %d\n", *p); // fetch value from p
There is another case which you could see p *
typedef int p;
p *aPtr = &i;
In this case we have created another name (a synonym) for type 'int' called 'p'. So here when we say 'p' it is translated to 'int' by the compiler. That way we can also say 'p *'.
精彩评论