为什么这两个整数变量和两个双变量(貌似)在内存中共享相同的地址?

Ale*_*drH 1 c++ memory pointers

我写了一个简单的程序,它有一个打印变量地址的方法和存储在该地址中的内容,只是为了帮助我更好地理解指针:

#include <iostream>
using std::cout;
using std::endl;


template<typename Type>
void PrintAddressAndContentsOf(Type Variable);


/* Entry point */
int main()
{
    int IntegerVariable1 = 5;
    int IntegerVariable2 = 6;

    double FloatingVariable1 = 10;
    double FloatingVariable2 = 11;

    PrintAddressAndContentsOf(IntegerVariable1);
    PrintAddressAndContentsOf(IntegerVariable2);
    PrintAddressAndContentsOf(FloatingVariable1);
    PrintAddressAndContentsOf(FloatingVariable2);
}


/* Prints the address and the corresponding contents of a given variable */
template<typename Type>
void PrintAddressAndContentsOf(Type Variable)
{
    Type* Pointer = &Variable;

    cout << "Address: " << Pointer << endl;
    cout << "Contents: " << *Pointer << endl;
}
Run Code Online (Sandbox Code Playgroud)

当我在Visual Studio上运行它时,我得到以下输出:

Address: 008FFB88
Contents: 5
Address: 008FFB88
Contents: 6
Address: 008FFB84
Contents: 10
Address: 008FFB84
Contents: 11
Run Code Online (Sandbox Code Playgroud)

如您所见,前两个整数似乎具有相同的008FFB88地址; 同样,两个浮点指针变量具有相同的地址008FFB84.

我的程序中是否存在缺陷,或者我是否缺少一些关键知识来理解这里发生了什么?

Nat*_*ica 8

这里的问题是你打印的是地址Variable,而不是main的变量地址.地址与Variable您初始化变量的地址无关,并且可以通过多次调用该函数来使用相同的地址.

如果我们改为引用,它给我们一个实际变量的别名,而不是像以下那样的副本:

template<typename Type>
void PrintAddressAndContentsOf(Type& Variable)
{
    Type* Pointer = &Variable;

    cout << "Address: " << Pointer << endl;
    cout << "Contents: " << *Pointer << endl;
}
Run Code Online (Sandbox Code Playgroud)

然后我们看到地址确实不同

Address: 0x7fffc8386ce8
Contents: 5
Address: 0x7fffc8386cec
Contents: 6
Address: 0x7fffc8386cf0
Contents: 10
Address: 0x7fffc8386cf8
Contents: 11
Run Code Online (Sandbox Code Playgroud)

  • @AleksandrH您需要`void PrintAddressAndContentsOf(Type&Variable)`或者如果您使用`PrintAddressAndContentsOf(const Type&Variable);`您需要将`Type*Pointer =&Variable;`更改为`const Type*Pointer =&Variable;` (2认同)