带有字符数组的c++ &运算符
c++ ampersand operator with char arrays
当我对我正在测试的这段代码感到困惑时,我只是在玩指针和数组。
#include <iostream>
using namespace std;
int main(void) {
char a[] = "hello";
cout << &a[0] << endl;
char b[] = {'h', 'e', 'l', 'l', 'o', ' '};
cout << &b[0] << endl;
int c[] = {1, 2, 3};
cout << &c[0] << endl;
return 0;
}
我期望这将打印三个地址(a[0], b[0]和c[0])。但结果是:
hello
hello
0x7fff1f4ce780
为什么对于char的前两种情况,'&'给出了整个字符串还是我在这里缺少了一些东西?
因为cout
的operator <<
打印一个字符串,如果你传递一个char*
作为参数,这就是&a[0]
。如果要打印地址,必须显式地将其强制转换为void*
:
cout << static_cast<void*>(&a[0]) << endl;
还是
cout << static_cast<void*>(a) << endl;
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<