【发布时间】:2019-02-03 05:02:11
【问题描述】:
在代码中:
int main(){
int a = 10;
int * s = &a;
cout << s;
}
“a”的内存地址按预期打印。但是,当我尝试时:
int main(){
char a = 10;
char * s = &a;
cout << s;
}
输出是一个垃圾值。这可能是什么原因?
【问题讨论】:
-
第一个片段调用
operator<<(void*)打印地址。第二个调用operator<<(const char*),它试图将参数解释为指向以 NUL 结尾的字符串的指针,并打印该字符串。如果你想要地址,请输入cout << static_cast<void*>(s); -
@IgorTandetnik - 继续写下去。清晰简洁的答案。