我想知道内部发生了什么,以及它与显示的值的关系。
代码如下:
# include <iostream>
int main(){
using namespace std;
const int a = 10;
int* p = &a; //When compiling it generates warning "initialization from int* to
//const int* discard const -- but no error is generated
cout << &a <<"\t" << p <<endl; //output: 0x246ff08 0x246ff08 (same values)
cout << a << "\t" << *p << endl; //output: 10 10
//Now..
*p = 11;
cout << &a <<"\t" << p <<endl; //output: 0x246ff08 0x246ff08 (essentially,
//same values and same as above, but..)
cout << a << "\t" << *p << endl; //output: 10 11
return 0;
}
问题: 如果p = a的地址, 那么a = 10, 但是*p = (跳转到a的地址并读取内存位置中的值) = 11,这是怎么回事?
const
char
的指针但实际上不修改指针,则这是可取的。如果您希望编译器执行更严格的限制,请考虑至少使用-pedantic
和-Werror
。 - Stuart Olsen