在c ++中获取常量变量的内存地址

时间:2015-06-07 18:37:57

标签: c++ pointers const

如何在c ++中获取常量变量的内存地址。当我试图得到这个时,我得到一个错误。

int const nValue = 5;
int * pnPtr = &nValue;

错误消息如下。我正在使用visual studio 2010。

Error   1   error C2440: 'initializing' : cannot convert from 'const int *' to 'int *'  

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

  

“有没有办法做到这一点?”

不确定。您需要一个const int*指针来获取此地址,如错误消息所示:

   int const nValue = 5;
   const int * pnPtr = &nValue;
// ^^^^^

int*指针允许修改nValue,这是不合法的,这就是编译器抱怨的原因。

至于你的评论。 const int*可用于指向常规int a const int。重点是你不能用它来修改它所拥有的地址的底层内存。

指针变量本身不是const,可以更改为其他地址。

如果你想要两个属性,你需要写:

    const int const * pnPtr = &nValue;
 // ^         ^ 
 // |         + prevents changing the pointer after initialization
 // +- prevents changing the underlying memory

答案 1 :(得分:1)

您需要使用指向const int值的指针,如下所示:

int const *ptr = &nValue;

C ++对于const-correctness是严格的,这是一件好事。