2017-09-27 83 views
0

我不知道为什么这个程序的输出是它是什么。也许有人可以帮助我。引用双指针的值是什么?

?为什么双指针的参考:0062FB78?

为什么提领双指针= 0062FAA0的参考?

Should'nt这些翻转?

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 
+3

注意要传递的参数*按值*到您的各种功能。 – Bathsheba

+5

调用'&x'“参考”有点混乱。它是'x'的地址而不是参考 – user463035818

+2

在你的函数中,'&x'是参数的地址。这不是您传递给函数的值的地址。 – molbdnilo

回答

2

在之前你去的问题,让我们先同意,调用y= &x后,y是不是x参考,而是x地址。

现在,让我们来看看在调用print

如果您密切关注,我们按值传递变量,因此这种方法实际上将打印出值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; 
}