[英]c++: pointer value different than address of the pointed variable
I just made a tiny stupid program about passing a variable the value contained in another using a pointer, just as an introduction to pointers themselves. 我只是做了一个很小的愚蠢程序,它使用指针将变量包含在另一个变量中的值传递给它,就像对指针本身的介绍一样。 I printed, before and after the assignation, the value and position of all three variables involved.
我在分配之前和之后打印了所涉及的所有三个变量的值和位置。 However, I get, as the value contained inside the pointer, an address different from the variable it is pointing to's one, and I just can't understand why.
但是,作为指针中包含的值,我得到了一个不同于它所指向的变量的地址,而我只是不明白为什么。
This is my main program: 这是我的主要程序:
#include <iostream>
#include "01.Point.h"
using namespace std;
int main()
{
int a,b;
cout << "Insert variable's value: ";
cin >> a;
int * point;
cout << "Before assignment:" << endl;
printeverything (a,b,point);
point = &a;
b = * point;
cout << "After assignment:" << endl;
printeverything (a,b,point);
cout << endl;
}
And this is my function's implementation: 这是我函数的实现:
#include <iostream>
#include "01.Point.h"
using namespace std;
void printeverything (int a, int b, int * c) {
cout << "First variable's value: " << a << "; its address: " << &a << endl;
cout << "Second variable's value: " << b << "; its address: " << &b << endl;
cout << "Pointer's value: " << c << "; its address: " << &c << endl;
}
b successfully gets a's value, so everything works right, but this is the complete output: b成功获取a的值,因此一切正常,但这是完整的输出:
Before assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 0; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b8a0; its address: 0x7fffee49b770
After assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 5; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b7ac; its address: 0x7fffee49b770
I mean, if variable x is at position 3285, and i do p = &x
, pointer p should contain value 3285, right? 我的意思是,如果变量x在位置3285,并且我做
p = &x
,则指针p应该包含值3285,对吗? So why is this happening? 那么为什么会这样呢?
In your printeverything
function, the parameter/local variable a
is an entirely different variable from the one you passed to it. 在您的
printeverything
函数中,参数/局部变量a
与传递给它的变量完全不同。 It happens to have the same name, but that's (as far as the compiler is concerned) entirely a coincidence - it's a different variable with a different address; 它恰好具有相同的名称,但是(就编译器而言)完全是巧合-它是一个具有不同地址的不同变量; you can see this by assigning a value to
a
within the function, and then printing it afterwards - you'll see that the "outer" a
will remain unchanged. 您可以通过在函数内为
a
分配一个值,然后在以后打印它来看到它-您将看到“外部” a
保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.