加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c带有char数组的&符号运算符

发布时间:2020-12-16 03:37:07 所属栏目:百科 来源:网络整理
导读:当我对我正在测试的这段代码感到困惑时,我只是在玩指针和数组. #include iostreamusing namespace std;int main(void) { char a[] = "hello"; cout a[0] endl; char b[] = {'h','e','l','o',''}; cout b[0] endl; int c[] = {1,2,3}; cout c[0] endl; retu
当我对我正在测试的这段代码感到困惑时,我只是在玩指针和数组.
#include <iostream>
using namespace std;

int main(void) {
    char a[] = "hello";
    cout << &a[0] << endl;
    char b[] = {'h','e','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的运算符<<如果你传给一个char *作为参数,那就打印一个字符串,这就是& a [0].如果要打印地址,则必须明确将其转换为void *:
cout << static_cast<void*>(&a[0]) << endl;

要不就

cout << static_cast<void*>(a) << endl;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读