سؤال

I am confused between the following two declarations:

int *p=&a; //first

and

int *p; //second
p=&a;

Asterisk * is not acting as dereference operator. Most of the places I have seen that * acts as dereference operator. My question is that, apart from first case, is there any case where * operator does not act as dereference operator?

هل كانت مفيدة؟

المحلول

* acts as a dereference operator only in an expression.

The (admittedly odd) syntax of C declarations is based on the idea that "declaration follows use". So these declarations:

int i;
int *p;

can be read as "i is an int" and *p is an int. Since *p is an int, then p must be a pointer-to-int.

(Of course * is also the multiplication operator if it appears with two operands.)

نصائح أخرى

In the declaration statement * is considered not a dereference operator but a part of a type specifier. int *p means that p is a pointer to int, and your first line also initializes it to the address of a. The second line assigns the address of a to p in a normal assignment statement.

p is still just a variable holding something. It's best you assign to it addresses of other variables, but you could assign to it whatever you wanted (some compilers will make it difficult, though) and then crash your program by dereferencing it!

Although the formal definition in the C standard is different, * does act like a dereference operator in declarations. The notion behind C declarations is that they show the type that an expression would have. For example, int *p; essentially says “When I dereference p, the result should be an int.”

So, although this is not an expression that deferences p, it is illustrating one.

& operator returns the memory address of the variable a, thus p will point to the memory location of variable a .

The * operator is called the indirection or also deference operator. It returns the contents of the memory location pointed to.

int *p; p is declared as a pointer to int
p = &a; p will point to the address of a

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top