变量值及其地址使用C++中的指针
variable value and its address using pointers in C++
我在理解指针方面遇到了一些问题。在下面的代码中,我尝试用两种方式打印变量的地址,一种是使用地址运算符,另一种是用指针:
#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;
}
x address = 0028FCC4
x address w pointer = 0028FCC4
这是意料之中的事。但当我做同样的事情,但现在使用字符类型变量时,我会得到一些垃圾输出:
#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;
}
address using address operator=Q╠╠╠╠£åbªp é
address pointed by pointer=Q╠╠╠╠£åbªp é
我不知道为什么会发生这种事。提前感谢。
C++库重载<lt;运算符。(char*)就是其中之一。Cout正在尝试打印一个字符串,一个以null字符结尾的字符数组。
只需投射指针:
cout << "address pointed by pointer" << ( void* )char_pointer << endl;
或
cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
它打印出垃圾的原因是因为你的char没有null终止符,这意味着程序会一直搜索一个,直到,在这个过程中,它会打印出它找到的任何东西。您看到的文本是ASCII,但被ostream误解的地址引用。要获取内存中的地址,可以使用隐式转换或static_cast。我更喜欢后者:
cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl;
就像2501所说的,用不同的措辞,&c
,因为c是char
,等于char *
,所以它将尝试打印,直到隐式或显式放入到std::cout
的字符数组中的新行字符' '
,这样流就知道字符数组的末尾在哪里。
所以,是的,像2501说的那样使用(void*)。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错