我在理解指针时遇到了一些麻烦.在下面的代码中,我尝试以两种方式打印变量的地址 - 一次使用地址运算符然后使用指针:
#include<iostream>
using namespace std;
int main (void)
{
int x = 10;
int *int_pointer;
int_pointer = &x;
cout << "x address=" << &x << endl;
cout << "x address w pointer=" << int_pointer << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
x address = 0028FCC4
x address w pointer = 0028FCC4
Run Code Online (Sandbox Code Playgroud)
这按预期工作.但是,当我做同样的事情,但现在使用字符类型变量,我得到一些垃圾输出:
#include<iostream>
using namespace std;
int main(void)
{
char c = 'Q';
char *char_pointer;
char_pointer = &c;
cout << "address using address operator=" << &c << endl;
cout << "address pointed by pointer=" << char_pointer << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
address using address operator=Q????£åbªp é
address pointed by pointer=Q????£åbªp é
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会这样.提前致谢.
C++库为某些类型重载<<运算符.(char*)就是其中之一.Cout正在尝试打印一个字符串,一个由空字符终止的字符数组.
刚刚施放指针:
cout << "address pointed by pointer" << ( void* )char_pointer << endl;
Run Code Online (Sandbox Code Playgroud)
要么
cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |