# Pointer clarification

• 02-23-2003
Spectrum48k
Pointer clarification
i was wondering if someone can clarify something for me.
after declaring a pointer eg. int *p;
sometimes its assigned a value like p=x or
p=&x or *p=x

my question is this. i understand p=&x assigns the memory
address of x to p, but when do you use *p=x and
when p=x ?

i am doing a lot of exercises mechanically while not fully digesting this, and its bugging me.
• 02-23-2003
MrWizard
I'm assuming that 'x' is a regular integer. Like you said, the statement p = &x will assign the pointer p to the address of x. *p = x assigns the value of x to wherever the pointer p points to. In this case that would do nothing because the value of p is already x since that is what it was initialized to. You can't say p = x because p is a pointer and x is an integer. You can do this is x is also a pointer.

Example:

Code:

```int main( void ) {   int *p = NULL; // Doesn't point to anything yet.   int y = 5; // Regular variable   int x = 2; // Regular variable   p = &x; // Now pointing to x   // Output value contained at memory address   cout << "x = " << x << endl;   cout << "*p = " << *p << endl;   // Change value at memory address to value of y   *p = y;   // Now the value of x has changed   cout << "x = " << x << endl;   cout << "*p = " << *p << endl;   return 0; }```
• 02-23-2003
R.Stiltskin
Quote:

my question is this. i understand p=&x assigns the memory
address of x to p, but when do you use *p=x and
when p=x ?
Since p is a pointer, *p = x will copy the value stored in x to the memory location referenced by p. (It would not make sense to do this after doing p = &x since then p would be pointing to x so it would be equivalent to saying x = x.)

You would NEVER do p = x unless x is also a pointer. Since p is a pointer type, that means it is a variable that can only hold pointer values (memory addresses); you can't give it an int value (or float, or char, etc).
• 02-23-2003
Spectrum48k
so since p=&x means p is pointing to th memory address
of x, any value i pass to p will go to the address of x, thus
manipulating x through its address. is this correct ?
• 02-23-2003
golfinguy4
Basically yeah...

*p=5; will set x equal to 5.