Setting an address and Initialization of a pointer
first, I'm sorry for my poor English, it's not my first language.
It's my first time to study about pointers and I found somthing really weird.
The book I'm reading says *
marker means a variable that the 'pa' indicates.
But when I try and initialize a pointer
int a;
int *pA =&a;
(they开发者_如何学Python used *pA
in this case) and then change it,
*pA=&a;
doesn't work, and
pA=&a;
works.
So my query is "is there any difference between initializing pointers and just substituting?"
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.
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` */
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
.
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.
精彩评论