Home > OS >  Pointer exercise in C
Pointer exercise in C

Time:12-27

I am currently preparing for an exam, and refreshing my pointer knowledge.

I am looking at this small exercise:

Consider the follow fragments of C programs. For each program, fill in the empty underlined spots such that the final value of the variable x is 0.

int x;
int *p;
p = &_____;
*p = _____;

I assume that the first underline is p = &x. I am little confused about the second one though. What is the difference between p = and *p = in this situation, given that we already have int *p?

CodePudding user response:

int *p;

... declares p as a variable of type int * (a pointer to int). Given that this code overall can be valid only if it appears inside a function, that declaration does not assign a value to p. As a result, the expression *p is not (yet) meaningful immediately after that declaration, despite being syntactically correct.

The subsequent

p = 

assigns a value to (pointer) p. Your idea of p = &x; seems plausible. But this is about the value of pointer p itself, not about the value of the object to which p points.

Once p actually points to an object courtesy of the assignment to it, the value of the object to which it points can be accessed via *p, and in particular, a value can be assigned to the pointed-to object via *p = <value here>;.

Perhaps the thing tripping you up is that in no case is the * part of the name of the pointer. In the declaration on line 2, it is part of the type (int *) declared for variable p. In the assignment on line 4, it is a unary operator applied to variable p.

  • Related