我无法弄清楚为什么这个程序的输出就是这样。也许有人可以帮助我。
为什么双指针的引用:0062FB78?
为什么取消引用双指针的引用= 0062FAA0?
这些不应该被翻转吗?
0062FB78是x
的地址我猜0062FAA0是双指针的地址?
#include <iostream>
void print(int x) {
std::cout << "value: " << (x) << "\n";
std::cout << "reference: " << (&x) << "\n";
//std::cout << (*x) << "\n";
}
void printPointer(int *x) {
std::cout << "value: " << x << "\n";
std::cout << "reference: " << &x << "\n";
std::cout << "dereference:" << *x << "\n";
}
void printDoublePointer(int **x) {
std::cout << "value: " << x << "\n";
std::cout << "reference: " << &x << "\n";
std::cout << "dereference:" << *x << "\n";
printPointer(*x);
}
void printTripplePointer(int ***x) {
std::cout << "value:" << x << "\n";
std::cout << "reference:" << &x << "\n";
std::cout << "dereference:" << *x << "\n";
printDoublePointer(*x);
}
void print(char* string) {
std::cout << "\n" << string << "\n";
}
int main()
{
int x = 19;
int *y; // y is a address space
y = &x; // &y now points to the address of x, *y now has the value of x
int **doublePointer = &y;
print(x);
printPointer(y);
printDoublePointer(doublePointer);
print("doublePointer");
std::cin >> x;
}
x
value: 19
reference: 0062FBB78
y
value: 0062FC7C
reference: 0062FBB78
defererence: 19
doublePointer
value: 0062FC58
reference of double Pointer: 0062FB78
dereference of doble Pointer: 0062FC7C
value of dereferenced double pointer: 0062FC7C
reference of dereferenced double pointer: 0062FAA0
dereference: 19
答案 0 :(得分:2)
在回答您的问题之前,我们首先同意在致电y= &x
后,y不是x
的引用,而是x
的地址。
现在,让我们检查对print
如果密切关注,我们会传递变量by-value,因此此方法实际上会打印值19
,但该地址将属于x
的临时副本。
如果我们将原型更改为以下原型,则此处打印的x
地址将等于方法y
printPointer
地址
void print(int & x) {
std::cout << __PRETTY_FUNCTION__ << "\n";
std::cout << "value: " << (x) << "\n";
std::cout << "reference: " << (&x) << "\n";
}
关于你的其他问题,这些问题也会发生,因为你按指令传递指针而不是按引用传递。
这个简单的程序显示一切正常:
int main()
{
int x = 19;
int *y = &x;
int **z = &y;
std::cout << x << "\t" << &x << std::endl;
std::cout << y << "\t" << &y << "\t" << *y << std::endl;
std::cout << z << "\t" << &z << "\t" << *z << std::endl;
}