tags:

views:

90

answers:

4
A: 

When you create a pointer you use

int *pA;

Afterwards, using *pA means you're accessing the value pointed to by the pointer.

When you use &a you are using the Address-of Operator which returns the address of the memory location in which the data stored of the variable a (which is a integer) is stored.

So, the correct assignment is pA = &a since you're copying the address of a to pA which is supposed to hold addresses of memory locations.

But *pA represents the value in that memory location (an integer) so it is incorrect to assign an address to *pA - this is why the right syntax is pA = &a.

Jacob
A: 

Yeah, when you first declare a pointer, you can specify the memory address. Because you are declaring it as a pointer, you use the * operator. But everywhere else, the *pA means to take the value referenced by that pointer (not the actual address). It is a little odd but you get used to it.

So, you can do this:

int a; 
int *pA = &a;

and you can do this:

pA = &a;

But you cannot do:

*pA = &a;

Because that says, "make the value pointed by pA = to the value of a."

However, you can do this:

*pA = a;

And that is just how you set the value pointed to by pA. Hope this is somewhat clear.

BobbyShaftoe
+2  A: 
int a;

This allocates an integer on the stack

int* pA = &a;

This allocates an int pointer on the stack and sets its value to point to a. The '*' is part of the declaration.

*pA = &a;

In this case the '*' is an operator that says "look where pA points", which is to an int. You are then trying to set that int to the address of a, which is not allowed.

pA = &a;

Now this is the same as the second statement. It sets the value of pA to point to a.

Jim Garrison
i'm also curious about when i'm allocating both a pointer and a variable.> int a, *p1;<--like thisand it works! make me think that '*' is included to the pointer.
Rhee
That's just shorthand for two separate declarations. The * is still part of the declaration (int *) of p1. I agree it's not completely intuitive, you just have to get used to it. In a declaration the * is part of the type. As an operator it has a different (but related) meaning.
Jim Garrison
A: 

In C, "declaration mimics use".

When you declare a pointer to int

int *pa;

you can see that pa is a int * or that *pa is a int.

You can assign pointers to int to pa, or you can assign ints to *pa.
That's why, after the above declaration, the following statements "work".

*pa = 42;
pa = &a;

In the declaration itself, you can "transform" it to a definition by supplying an initialization value. The definition is for the object pa of type int*, not for *pa.

int *pa = &a; /* initialize pa, which takes a `int*` */
pa = &b;      /* change `pa` with a different `int*` */
*pa = 42;     /* change the value pointed to by `pa` */
pmg