问题
If I run the following on OS X:
int main (void)
{
int* n; // initialise(declare) pointer
*n = 20; // the value in address pointed to by n is 20
printf("n: %i, n&: %i\n", n, &n);
return 0;
}
I get:
n: 1592302512, n&: 1592302480
Why the differing values?
回答1:
Why do
pointer
and&pointer
have different values?
The expression &n
yields the address of n
itself, while n
evaluates to the value of the pointer, i.e. the address of the thing it points to.
But note that you have undefined behaviour First of all, because you are de-referencing an uninitialized pointer. You need to make n
point somewhere you can write to.
For example,
int* n;
int i = 42;
n = &i;
// now you can de-reference n
*n = 20;
Second, you have the wrong printf
specifier for &n
. You need %p
:
printf("n: %i, &n: %p\n", n, &n);
回答2:
int* n
declares a variable called n
which is a pointer to an integer.&n
returns the address of the variable n
, which would be a pointer to a pointer-to-integer.
Let's say we have the following code:
int a = 20; // declare an integer a whose value 20
int* n = &a; // declare a pointer n whose value is the address of a
int** p = &n; // declare a pointer p whose value is the address of n
In this case we would have the following:
variable name | value | address in memory
a | 20 | 1592302512
n | 1592302512 | 1592302480
p | 1592302480 | who knows?
回答3:
In your code
int* n; //initialization is not done
*n = 20;
invokes undefined behavior. You're trying to de-reference (write into) uninitialized memory. You have to allocate memory to n
before de-referencing.
Apart form that part,
n
is of typeint *
&n
will be of typeint **
So, they are different and supposed to have different values.
That said, you should use %p
format specifier with printf()
to print the pointers.
回答4:
Just as an alternative, let me spell this out a different way.
char *ptr;
char c='A';
ptr = &c;
In this code, here's what's happening and what values are found when we qualify ptr
in different ways.
ptr
itself contains the address in memory where the char c
variable is located.
*ptr
dereferences the pointer, returning the actual value of the variable c
. In this case, a capital A.
&ptr
will give you the address of the memory location that ptr
represents. In other words, if you needed to know where the pointer itself was located rather than what the address is of the thing that it points to, this is how you get it.
来源:https://stackoverflow.com/questions/28418854/c-why-do-pointer-and-pointer-have-different-values