You need the asterisk when you are declaring a pointer, or when you are dereferencing the pointer. The syntax actually is the same in both functions, but what is being assigned in each of the assignment statements is different.
An int
is a value. An int
variable is stored in a storage location. A pointer to an int
is also a value, but its value refers to a storage location. When you are performing an assignment with a pointer, you could assign the value of the pointer itself (the address of the storage location it refers to), or you could assign a value to the storage location it refers to.
In the case of int *x
in the formal parameters of the function, or in the declaration int *ab
that defines the ab
variable, you need the asterisk because you are declaring a variable or a parameter to be of type "pointer to int".
In the assignment ab = &a
you do not need the asterisk because you are assigning the address of variable a
to the pointer ab
-- you are assigning the value of the pointer itself, not what it points to.
In the assignment *x = 9001
, you need the asterisk to get the storage location that the pointer refers to. This is called "dereferencing" the pointer. You are not assigning a value to the pointer itself, but instead you are assigning a value to the storage location to which the pointer refers, which is the storage allocated for variable a
in function main
.
This article by Eric Lippert may be of considerable help to you:
What are the fundamental rules of pointers?